10

I'm not sure, but it appears to me that the default implementation of .NET HttpClient library is flawed. It looks like it sets the Content-Type request value to "text/html" on a PostAsJsonAsync call. I've tried to reset the request value, but not sure if I'm doing this correctly. Any suggestions.

public async Task<string> SendPost(Model model)
{
    var client = new HttpClient();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    var response = await client.PostAsJsonAsync(Url + "api/foo/", model);
    response.EnsureSuccessStatusCode();
    return await response.Content.ReadAsStringAsync();    
}
user167698
  • 1,833
  • 6
  • 20
  • 25
  • Can you post the error you got back? IMHO, the code should work, as someone else posted on SO: http://stackoverflow.com/questions/10679214/how-do-you-set-the-content-type-header-for-an-httpclient-request – Henry Liang Jan 04 '16 at 20:27
  • 4
    The error I'm getting is a general "bad reqest (400 status code)". It appears the default content-type value is set to "text/html", instead of "application/json". You would think a method named, PostAsJsonAsync would automatically set this! – user167698 Jan 04 '16 at 20:58
  • 1
    I am also getting this issue? Why would the `PostAsJson` not set the content type to json? it just doesn't make sense. – Zapnologica Nov 03 '21 at 03:51

1 Answers1

9

You should set the content type. With the Accept you define what you want as response.

http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html The Accept request-header field can be used to specify certain media types which are acceptable for the response. Accept headers can be used to indicate that the request is specifically limited to a small set of desired types, as in the case of a request for an in-line image.

public async Task<string> SendPost(Model model)
{
    var client = new HttpClient(); //You should extract this and reuse the same instance multiple times.
    var request = new HttpRequestMessage(HttpMethod.Post, Url + "api/foo");
    using(var content = new StringContent(Serialize(model), Encoding.UTF8, "application/json"))
    {
        request.Content = content;
        var response = await client.SendAsync(request).ConfigureAwait(false);
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
    }
}
Edwin van Vliet
  • 567
  • 2
  • 12