Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I force asp.net webapi to always decode POST data as JSON

I am getting some json data posted to my asp.net webapi, but the post parameter is always coming up null - the data is not being serialized correctly. The method looks something like this:

public HttpResponseMessage Post(string id, RegistrationData registerData)

It seems the problem is that the client (which I have no control over) is always sending the content-type as x-www-form-urlencoded, even though the content is actually json. This causes mvc to try to deserialize it as form data, which fails.

Is there any way to get webapi to always deserialize as json, and to ignore the content-type header?

like image 410
Nathan Avatar asked Sep 12 '12 10:09

Nathan


People also ask

How return only JSON from ASP Net Web API service irrespective of the Accept header value?

We see that in a bit. How to return only JSON from ASP.NET Web API service. Now whenever we are going to request the service is always going to format the data using JSON Formatter irrespective of the acceptheader value in the request. You can use this in service when it only supports JSON data.

What is the best approach for requesting JSON instead of XML from API?

So for JSON you don't have to write any special code in C# since that is already there in Web API, but you need to make sure that you send an appropriate ajax request from jQuery. For JSON response when using jQuery, you should use jQuery AJAX request as below with dataType: "json".


2 Answers

I found the answer here: http://blog.cdeutsch.com/2012/08/force-content-types-to-json-in-net.html

This code needs to be added to Application_Start or WebApiConfig.Register

foreach (var mediaType in config.Formatters.FormUrlEncodedFormatter.SupportedMediaTypes) 
{
    config.Formatters.JsonFormatter.SupportedMediaTypes.Add(mediaType);
}

config.Formatters.Remove(config.Formatters.FormUrlEncodedFormatter);
config.Formatters.Remove(config.Formatters.XmlFormatter);

It tells the json formatter to accept every type, and removes the form and xml formatters

like image 112
Nathan Avatar answered Oct 20 '22 15:10

Nathan


I would suggest to rather modify the incoming request's content-type, let's say at the message handler to the appropriate content-type, rather than removing the formatters from config

like image 42
Kiran Avatar answered Oct 20 '22 17:10

Kiran