How do you set the Content-Type header for an HttpClient request? How do you set the Content-Type header for an HttpClient request? asp.net asp.net

How do you set the Content-Type header for an HttpClient request?


The content type is a header of the content, not of the request, which is why this is failing. AddWithoutValidation as suggested by Robert Levy may work, but you can also set the content type when creating the request content itself (note that the code snippet adds application/json in two places-for Accept and Content-Type headers):

HttpClient client = new HttpClient();client.BaseAddress = new Uri("http://example.com/");client.DefaultRequestHeaders      .Accept      .Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT headerHttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "relativeAddress");request.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}",                                    Encoding.UTF8,                                     "application/json");//CONTENT-TYPE headerclient.SendAsync(request)      .ContinueWith(responseTask =>      {          Console.WriteLine("Response: {0}", responseTask.Result);      });


For those who didn't see Johns comment to carlos solution ...

req.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");


If you don't mind a small library dependency, Flurl.Http [disclosure: I'm the author] makes this uber-simple. Its PostJsonAsync method takes care of both serializing the content and setting the content-type header, and ReceiveJson deserializes the response. If the accept header is required you'll need to set that yourself, but Flurl provides a pretty clean way to do that too:

using Flurl.Http;var result = await "http://example.com/"    .WithHeader("Accept", "application/json")    .PostJsonAsync(new { ... })    .ReceiveJson<TResult>();

Flurl uses HttpClient and Json.NET under the hood, and it's a PCL so it'll work on a variety of platforms.

PM> Install-Package Flurl.Http