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

I get some json data sent to my asp.net webapi, but the post parameter always approaches zero - the data is not being serialized correctly. The method looks something like this:

public HttpResponseMessage Post(string id, RegistrationData registerData) 

The problem seems to be that the client (which I don't control) always sends the content type as x-www-form-urlencoded , although the content is actually json. This causes mvc to try to deserialize it as form data, which fails.

Is there a way to make webapi always deserialize as json and ignore the content header?

+5
source share
2 answers

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

This code must 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 json formatter to accept all types and removes form and xml formatters

+8
source

I would rather rather modify the content type of the incoming request, for example, in the message handler, the corresponding content type, and not remove the formatting elements from config

+1
source

All Articles