How to send JSON in C# with DataContractJsonSerializer without charset?

royco picture royco · Apr 19, 2013 · Viewed 10.4k times · Source

I use DataContractJsonSerializer and StringContent to send JSON to a web service:

DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Employee));
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, employee);
ms.Position = 0;
StreamReader sr = new StreamReader(ms);
StringContent jsonContent = new StringContent(sr.ReadToEnd(),
                               System.Text.Encoding.UTF8, "application/json");
// later I do HttpClient.PostAsync(uri, jsonContent)

This results in this Content-Type header:

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

Is it possible to leave off the charset and just have the following header?

Content-Type: application/json

I don't see an overload on StringContent which does this.

Answer

Vadim Gremyachev picture Vadim Gremyachev · May 24, 2015

When a new instance of the StringContent class is initialized via

public StringContent(
    string content,
    Encoding encoding,
    string mediaType
)

following HTTP request header for Content Type is generated:

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

Pay attention to the presence of encoding part ( charset=utf-8)

In order to construct Content Type header without encoding part, the following options could be considered:

1) Using StringContent Constructor (String) and setting content type using ContentType property, for example:

var requestContent = new StringContent(jsonContent);                
requestContent.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json");

or

var requestContent = new StringContent(jsonContent);                
requestContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

2) Remove encoding part from ContentType property, for example:

    var requestContent = new StringContent(jsonContent, System.Text.Encoding.UTF8, "application/json");
    requestContent.Headers.ContentType.CharSet = null; 

3) Create custom JsonMediaTypeFormatter Class that resets encoding part:

public class NoCharsetJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
    public override void SetDefaultContentHeaders(Type type, System.Net.Http.Headers.HttpContentHeaders headers, System.Net.Http.Headers.MediaTypeHeaderValue mediaType)
    {
        base.SetDefaultContentHeaders(type, headers, mediaType);
        headers.ContentType.CharSet = null;
    }
}