Serialization of default values Web Api and Json.NET

If you’re using ASP.NET Web Api and some properties isn’t serialized when serializing to json if the value is default value. An example is when bool properties with false as value not are serialized try to add the following code in the Register method of the WebApiConfig class.

config.Formatters.JsonFormatter.SerializerSettings.DefaultValueHandling =

415 Unsuported media type

A common error when posting JSON to a WebAPI service is “415 Unsupported Media Type”. When posting JSON with HttpClient you added your JSON to StringContent and using Uri and StringContent as argument for PostAsync. The code below resulting in above mentioned error.

var content = new StringContent(json);
await client.PostAsync(uri, content);

The first thought is often to set content type on the HttpClient. But in this case it will not be the right solution.

It easy to miss that the StringContent constructor has two overloads that receives media type. The code below will make the error to disappear.

var content = new StringContent(json, Encoding.UTF8, "application/json");
await client.PostAsync(uri, content);