Rectangle 27 1

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


"Cannot send a content-body with this verb-type."
HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Get, @"myUrl");
httpRequest.Content = new StringContent(string.Empty, Encoding.UTF8, "application/json");

HttpClient client = new HttpClient();
Task<HttpResponseMessage> response =  client.SendAsync(httpRequest);  //I know I should have used async/await here!
var result = response.Result;

@TarekEl-Mallah Yes - please read the comments in my answer. The whole point of my post was to illustrate that it doesn't work in .NET 4, but it does work in .NET core (they are not the same thing). You will have to see erdomeke's answer to the OP's question to be able to hack it to work in .NET 4.

However, if i do the same thing with .NET Core (1.1) - I don't get an exception. My request was quite happily answered by my server application, and the content-type was picked up.

I have tried the following code using .Net 4.6:

I was pleasantly surprised about that, and I hope it helps someone!

Some extra information about .NET Core (after reading erdomke's post about setting a private field to supply the content-type on a request that doesn't have content)...

Thanks, Jay -- Not using core, and will use erdomke's answer. I appreciate knowing that all reasonable avenues have been tried :).

not working .net 4 ({"Cannot send a content-body with this verb-type."})

works fine in .NET Core indeed, thanks!

Note
Rectangle 27 1

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


PM> Install-Package Flurl.Http
PostUrlEncodedAsync
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.

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:

Note
Rectangle 27 1

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


PM> Install-Package Flurl.Http
PostUrlEncodedAsync
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.

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:

Note
Rectangle 27 1

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


HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://example.com/");
client.DefaultRequestHeaders
      .Accept
      .Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header

HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "relativeAddress");
request.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}",
                                    Encoding.UTF8, 
                                    "application/json");//CONTENT-TYPE header

client.SendAsync(request)
      .ContinueWith(responseTask =>
      {
          Console.WriteLine("Response: {0}", responseTask.Result);
      });

@AshishJain Most of the SO answers I've seen involving Response.Content.Headers for the ASP.Net Web API haven't worked either, but you can easily set it using HttpContext.Current.Response.ContentType if you need to.

Alternatively, Response.Content.Headers will work most of the time.

Content-Type is a property of an HTTP message with payload; it has nothing to do with request vs response.

Not working for me. My requiremnt is same, my i written same but not working for me. :(

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 use set the content type when creating the request content itself (note that code snippet adds "application/json" in two places-for Accept and Content-Type headers):

Note
Rectangle 27 1

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


HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://example.com/");
client.DefaultRequestHeaders
      .Accept
      .Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header

HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "relativeAddress");
request.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}",
                                    Encoding.UTF8, 
                                    "application/json");//CONTENT-TYPE header

client.SendAsync(request)
      .ContinueWith(responseTask =>
      {
          Console.WriteLine("Response: {0}", responseTask.Result);
      });

@AshishJain Most of the SO answers I've seen involving Response.Content.Headers for the ASP.Net Web API haven't worked either, but you can easily set it using HttpContext.Current.Response.ContentType if you need to.

Alternatively, Response.Content.Headers will work most of the time.

Content-Type is a property of an HTTP message with payload; it has nothing to do with request vs response.

Not working for me. My requiremnt is same, my i written same but not working for me. :(

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 use set the content type when creating the request content itself (note that code snippet adds "application/json" in two places-for Accept and Content-Type headers):

Note
Rectangle 27 1

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


"Cannot send a content-body with this verb-type."
HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Get, @"myUrl");
httpRequest.Content = new StringContent(string.Empty, Encoding.UTF8, "application/json");

HttpClient client = new HttpClient();
Task<HttpResponseMessage> response =  client.SendAsync(httpRequest);  //I know I should have used async/await here!
var result = response.Result;

@TarekEl-Mallah Yes - please read the comments in my answer. The whole point of my post was to illustrate that it doesn't work in .NET 4, but it does work in .NET core (they are not the same thing). You will have to see erdomeke's answer to the OP's question to be able to hack it to work in .NET 4.

However, if i do the same thing with .NET Core (1.1) - I don't get an exception. My request was quite happily answered by my server application, and the content-type was picked up.

I have tried the following code using .Net 4.6:

I was pleasantly surprised about that, and I hope it helps someone!

Some extra information about .NET Core (after reading erdomke's post about setting a private field to supply the content-type on a request that doesn't have content)...

Thanks, Jay -- Not using core, and will use erdomke's answer. I appreciate knowing that all reasonable avenues have been tried :).

not working .net 4 ({"Cannot send a content-body with this verb-type."})

works fine in .NET Core indeed, thanks!

Note
Rectangle 27 1

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


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

"application/binary" is not a MIME media type. Instead use "application/octet-stream".

I had to throw .ToString() on the end, but yes this worked for a WCF service implementation.

It made difference downloading a pdf. From the phone it tried to download an HTML. After converting the extension the file was normally encoded.

Note
Rectangle 27 1

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


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

I had to throw .ToString() on the end, but yes this worked for a WCF service implementation.

It made difference downloading a pdf. From the phone it tried to download an HTML. After converting the extension the file was normally encoded.

Note
Rectangle 27 1

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


var client = new HttpClient();
  client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json; charset=utf-8");
Note
Rectangle 27 1

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


var client = new HttpClient();
  client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json; charset=utf-8");
Note