Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 339
royco Avatar asked Dec 02 '22 19:12

royco


1 Answers

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;
    }
}
like image 193
Vadim Gremyachev Avatar answered Dec 04 '22 07:12

Vadim Gremyachev