我怎么能强制asp.net的WebAPI总是去code POST数据作为JSON [英] How can I force asp.net webapi to always decode POST data as JSON

查看:165
本文介绍了我怎么能强制asp.net的WebAPI总是去code POST数据作为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到贴到我的asp.net的WebAPI一些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)

看来问题是,客户端(这是我无法控制的)总是发送内容类型的X WWW的形式urlen codeD,即使内容实际上是JSON。这将导致MVC尝试反序列化的表单数据,这将失败。

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.

有没有什么办法让的WebAPI总是反序列化的JSON和忽略的内容类型头?

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

推荐答案

我找到了答案在这里:<一href=\"http://blog.cdeutsch.com/2012/08/force-content-types-to-json-in-net.html\">http://blog.cdeutsch.com/2012/08/force-content-types-to-json-in-net.html

这code必须添加的Application_Start或WebApiConfig.Register

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

它告诉JSON格式接受每一种类型,并删除格式和XML格式化

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

这篇关于我怎么能强制asp.net的WebAPI总是去code POST数据作为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆