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 =
                                   Newtonsoft.Json.DefaultValueHandling.Include;

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);

Authentication for REST calls with HTTPClient to Azure MobileServies

In a current project I working with an app that uses a .NET Backend in Azure Mobile Services. Backend is a WebAPI.

On client side I have all the code for networking in portable class library so I can reuse it on other platforms. Right now we are building the app for Windows Phone, but the plan is to build it for both iOS and Android using Xamarin. I am using the HttpClient object to do the REST calls. HttpClient is not in portable class library per default. But if you download “Microsoft HTTP Client Libraries” from NuGet you will get it.

My first problem was about which credentials I should use for the REST call to Azure. You can only see the application key in the portal. Is that the password? And what is the username in that case? The answer is that the application key is the password and username is just an empty string.
Problem number two was how to specify the credentials. My first try was to add the as the code below shows.

var handler = new HttpClientHandler {Credentials = new NetworkCredential("", "appKey") };
 
var client = new HttpClient(handler);

But then I got a 401 (Unauthorized) error back. After some mail conversations with the always helpful Mobile Services team we consider that the problem probably was that the call does not try to authenticate with basic authentication. When I tried the code below instead of the code above it worked.

var client = new HttpClient();
                client.DefaultRequestHeaders.Authorization = 
                    new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes(String.Format("{0}:{1}", "", "appKey"))));