Izikon
Izikon

Reputation: 902

HttpClient send null POST data

Well... I read A LOT of questions here in StackOverflow, but still didn't get answer for it, I have this Web API controller:

public class ERSController : ApiController
{
    [HttpGet]
    public HttpResponseMessage Get()
    {
        var resposne = new HttpResponseMessage(HttpStatusCode.OK);
        resposne.Content = new StringContent("test OK");
        return resposne;
    }

    [HttpPost]
    public HttpResponseMessage Post([FromUri]string ID,[FromBody] string Data)
    {
        var resposne = new HttpResponseMessage(HttpStatusCode.OK);
        //Some actions with database
        resposne.Content = new StringContent("Added");
        return resposne;
    }

}

and I wrote a small tester to it:

static void Main(string[] args)
{
    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri("http://localhost:54916/");
    client.DefaultRequestHeaders.Accept.Clear();


    var content = new StringContent("<data>Hello</data>", Encoding.UTF8, "application/json");

    var response = client.PostAsync("api/ERS?ID=123", content);

    response.ContinueWith(p =>
    {
        string result = p.Result.Content.ReadAsStringAsync().Result;
        Console.WriteLine(result);
    });
    Console.ReadKey();
}

I always get NULL on the parameter Data in the API.

I tried adding those lines to the tester:

client.DefaultRequestHeaders
                           .Accept
                           .Add(new MediaTypeWithQualityHeaderValue("application/json"));

still NULL, I also replace the content with:

var values = new Dictionary<string, string>();
values.Add("Data", "Data");
var content = new FormUrlEncodedContent(values);

still NULL.

I tried switching the request to:

WebClient client = new WebClient();
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";

var values = new NameValueCollection();
values["Data"] = "hello";
var task = client.UploadValuesTaskAsync("http://localhost:54916/api/ERS?ID=123", values);
task.ContinueWith((p) =>
{
    string response = Encoding.UTF8.GetString(p.Result);
    Console.WriteLine(response);
});

but debugger still saying 'NO!' the Data is still NULL.

I do get the ID with no problem.

Upvotes: 1

Views: 6521

Answers (1)

Marcos Dimitrio
Marcos Dimitrio

Reputation: 6852

If you want to send it as a JSON string, you should do this (using Newtonsoft.Json):

var serialized = JsonConvert.SerializeObject("Hello");
var content = new StringContent(serialized, Encoding.UTF8, "application/json");

You almost got it right with FormUrlEncodedContent, what you had to do was send it with an empty name, like in this example:

var content = new FormUrlEncodedContent(new[]
{
    new KeyValuePair<string, string>("", "Hello")
});

var response = client.PostAsync("api/ERS?ID=123", content);

Upvotes: 5

Related Questions