How do you set the Content-Type header for an HttpClient request? [c#]


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

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


I'm trying to set the Content-Type header of an HttpClient object as required by an API I am calling.

I tried setting the Content-Type like below:

using (var httpClient = new HttpClient())
    httpClient.BaseAddress = new Uri("");
    httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
    httpClient.DefaultRequestHeaders.Add("Content-Type", "application/json");
    // ...

It allows me to add the Accept header but when I try to add Content-Type it throws the following exception:

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

How can I set the Content-Type header in a HttpClient request?

C# HttpClient ProtocolViolationException

Do not set a Content-Type in the GET request. Instead, assuming that you would like to receive a JSON result, set the Accept header.

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?


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

The latest and greatest answer to this with Flurl is to upgrade. 2.0 introduces several enhancements in the headers dept:

  1. They're no longer validated. Flurl now uses TryAddWithoutValidation under the hood, so you'll never get the "misused header name" error with the WithHeader(s) methods. (I always found that validation behavior to be a bit overprotective.)

  2. In a fluent call they're set at the individual request level rather than the FlurlClient level, so you won't run into concurrency issues when reusing the client.

  3. Since hyphens are common in header names but not allowed in C# identifiers, there's a new convention where underscores are converted to hyphens so you don't have to give up object notation when specifying multiple:

    url.WithHeaders(new { Content_Type = "foo", ... }