[SOLVED] How to remove charset=utf8 from Content-Type header generated by HttpClient.PostAsJsonAsync()?

Issue

I have an issue with
HttpClient.PostAsJsonAsync()

In addition to “application/json” in the “Content-Type” header the method also adds “charset=utf-8”

so the header looks like this:

Content-Type: application/json; charset=utf-8

While ASP.NET WebAPI doesn’t have any issue with this header, i’ve found that other WebAPIs I work against as a client don’t accept request with this header, unless it’s only application/json.

Is there anyway to remove the “charset=utf-8” from Content-Type when using PostAsJsonAsync(), or should I use another method?

SOLUTION:
Credits to Yishai!

using System.Net.Http.Headers;

public class NoCharSetJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
   public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)
   {
       base.SetDefaultContentHeaders(type, headers, mediaType);
       headers.ContentType.CharSet = "";
   }
}

public static class HttpClientExtensions
{
    public static async Task<HttpResponseMessage> PostAsJsonWithNoCharSetAsync<T>(this HttpClient client, string requestUri, T value, CancellationToken cancellationToken)
    {
        return await client.PostAsync(requestUri, value, new NoCharSetJsonMediaTypeFormatter(), cancellationToken);
    }

    public static async Task<HttpResponseMessage> PostAsJsonWithNoCharSetAsync<T>(this HttpClient client, string requestUri, T value)
    {
        return await client.PostAsync(requestUri, value, new NoCharSetJsonMediaTypeFormatter());
    }
}

Solution

You can derive from JsonMediaTypeFormatter and override SetDefaultContentHeaders.

Call base.SetDefaultContentHeaders() and then clear headers.ContentType.CharSet

then write your own extension method based on the following code:

public static Task<HttpResponseMessage> PostAsJsonAsync<T>(this HttpClient client, string requestUri, T value, CancellationToken cancellationToken)
{
    return client.PostAsync(requestUri, value, 
            new JsonMediaTypeFormatter(), cancellationToken);
}

In essence something like:

public static Task<HttpResponseMessage> PostAsJsonWithNoCharSetAsync<T>(this HttpClient client, string requestUri, T value, CancellatioNToken cancellationToken)
{
    return client.PostAsync(requestUri, value, 
          new NoCharSetJsonMediaTypeFormatter(), cancellationToken);
}

Answered By – Yishai Galatzer

Answer Checked By – Marie Seifert (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *