Lev*_*kon 8 asp.net-mvc-4 asp.net-web-api
我正在加速使用MVC 4的Web API,我对默认格式有点困惑.我希望API数据是JSON.但是,它以XML格式返回.根据MVC 4入门视频http://www.asp.net/web-api/videos/getting-started/your-first-web-api,默认情况下它应该是JSON.但是当我创建一个新的Web Api项目并运行该示例时,我得到了这个:
<ArrayOfstring><string>value1</string><string>value2</string></ArrayOfstring>
Run Code Online (Sandbox Code Playgroud)
我一直在试图用JSON试图获得这个,但显然有很多关于此的错误信息.如:
GlobalConfiguration.Configuration.Formatters.Insert(0, new JsonNetFormatter(serializerSettings));它应该做的伎俩.但我收集了这个折旧,因为没有一个例子正在运作.我可以做些什么,最好是简单的,默认输出JSON格式的数据?
Jus*_*tin 19
将其添加到GLOBAL.ASAX以获取响应为application/json
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
Run Code Online (Sandbox Code Playgroud)
所以它应该在上下文中看起来像这样:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
BundleTable.Bundles.RegisterTemplateBundles();
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您需要将XML保留为媒体类型,则可以编辑App_Start/WebApiConfig.cs:
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html") );
Run Code Online (Sandbox Code Playgroud)
这使得JSON成为Web浏览器的默认响应,但返回text/html.
| 归档时间: |
|
| 查看次数: |
16051 次 |
| 最近记录: |