.NET HttpClient Request Content-Type

30,095

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);
    }
}
Share:
30,095
user167698
Author by

user167698

Updated on July 16, 2022

Comments

  • user167698
    user167698 almost 2 years

    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();    
    }
    
  • Esben Skov Pedersen
    Esben Skov Pedersen over 8 years
    Why are you using ConfigureAwait(false)? Bad habit.
  • Edwin van Vliet
    Edwin van Vliet over 8 years
    I disagree. This part code is not dependent on the context, so it's better to use the ConfigureAwait(false) syntax. Here is some interesting read about it: msdn.microsoft.com/en-us/magazine/jj991977.aspx
  • Yuval Itzchakov
    Yuval Itzchakov over 8 years
    @Esben Why do you think ConfigureAwait(false) is a bad habit?
  • Esben Skov Pedersen
    Esben Skov Pedersen over 8 years
    I stand corrected. I've seen it as extra fluff but there seems to be a good reason for it.
  • Zapnologica
    Zapnologica over 2 years
    Buy this seems like a workaround. why not just use the PostAsJson() method on httpclient?