How to Set the Content-Type Header for an Httpclient Request

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 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);
});

How can I add Content-Type to header of http post method?

You could refer the following sample to set the Content-Type:

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://localhost:44310/api/todo/"); //Change the Uri and request content to yours.
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

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

And the web API method like this:

[HttpPost]
[Route("relativeAddress")]
public string GetAddress([FromBody]TestUserViewModel testUser)
{
return "Address A";
}

View Model:

public class TestUserViewModel
{
public string Name { get; set; }
public int Age { get; set; }
}

The result as below:

Sample Image

Explicitly Set Content-Type Headers For Get Operation in HttpClient

Based on my findings i concluded the HttpClient is very restrictive in terms of the protocol rules. I also reflected through the implementation DLL and i couldn't find anything that it would indicate that it allows protocol violations.

GET requests shouldn't have content-type headers, and the HttpClient is enforcing that rule.

I think the exception message when you try to set the content-type header is self-descriptive:

System.InvalidOperationException: Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.

Also if you use set the content body you get one more self-descriptive message:

System.Net.ProtocolViolationException: Cannot send a content-body with this verb-type.

Since you are willing to violate HTTP rules for GET requests i am pretty sure your only option is to stick with the less restrictive WebClient, which works in that scenario.

Can't set Content-Type header

I think you should try this

req.Content = new StringContent(rcString, Encoding.UTF8, "application/json");

checkout this links :

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

Edit

Remove this line c.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json"); and check



Related Topics



Leave a reply



Submit