MVC 4 - Web Api和JSON?

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试图获得这个,但显然有很多关于此的错误信息.如:

  1. 如果我将"application/json"添加到内容类型标头,它应该返回JSON.这不起作用,但我怀疑我没有正确的标题变量名称,因为我找不到要使用的确切名称.我在请求标题中尝试了"Content-Type"和"contentType",但没有运气.此外,我默认需要JSON,而不是根据标题信息.
  2. 如果我创建一个JsonFormatter并将其添加到Application_Start 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.

资源