5

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?

Nathan
  • 11,938
  • 12
  • 55
  • 62

2 Answers2

9

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

cuongle
  • 74,024
  • 28
  • 151
  • 206
Nathan
  • 11,938
  • 12
  • 55
  • 62
1

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

Kiran
  • 56,921
  • 15
  • 176
  • 161
  • Is it possible to apply a filter like this before the request is processed? I know how to do this in normal mvc, but not in webapi – Nathan Sep 12 '12 at 19:13
  • @NathanReed I am trying to do this in normal MVC :) How would you do it? – Zaid Masud Nov 08 '13 at 19:56