Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET HttpClient Request Content-Type

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();    
}
like image 629
user167698 Avatar asked Jan 04 '16 20:01

user167698


People also ask

What is Content-Type in post request?

The Content-Type representation header is used to indicate the original media type of the resource (prior to any content encoding applied for sending). In responses, a Content-Type header provides the client with the actual content type of the returned content.

What is DefaultRequestHeaders?

The DefaultRequestHeaders property represents the headers that an app developer can set, not all of the headers that may eventually be sent with the request. The HttpBaseProtocolFilter will add some additional headers.


1 Answers

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);
    }
}
like image 62
Edwin van Vliet Avatar answered Oct 15 '22 03:10

Edwin van Vliet