【问题标题】:Return json by default using ASP.NET Web API默认使用 ASP.NET Web API 返回 json
【发布时间】:2012-12-01 17:00:26
【问题描述】:

是否可以默认从 ASP.NET Web API 返回 json 而不是 XML?

【问题讨论】:

  • 这种方式打破了保持 web api 不可知的模式。如果您在 ajax 请求的标头中发送 Accept : application/json,WebAPI 将以 Json 响应。我可以看看你的 ajax 请求吗?
  • 谢谢伙计。这就是我所需要的。我刚刚看到了一个来自pluralsight的视频教程,它使用了web api,并且那个家伙把它放在了api url路由中,它直接在浏览器中响应了json。所以没有ajax请求。它只是 website.com/api/control
  • 您甚至不需要 Accept 标头。如果您在 GET 请求中没有 Accept 标头,您应该从 WebAPI 获取 JSON。

标签: asp.net-web-api mediatypeformatter


【解决方案1】:

这是默认完成的。 JsonMediaTypeFormatter 注册为第一个 MediaTypeFormatter,如果客户端未请求特定格式的响应,ASP.NET Web API 管道将为您提供application/json 格式的响应。

如果您只想支持application/json,请删除所有其他格式化程序并仅保留JsonMediaTypeFormatter

public static void Configure(HttpConfiguration config) {

    var jqueryFormatter = config.Formatters.FirstOrDefault(x => x.GetType() == typeof(JQueryMvcFormUrlEncodedFormatter));
    config.Formatters.Remove(config.Formatters.XmlFormatter);
    config.Formatters.Remove(config.Formatters.FormUrlEncodedFormatter);
    config.Formatters.Remove(jqueryFormatter);
}

【讨论】:

    【解决方案2】:

    @tugberk 的解决方案并没有真正实现更改默认格式化程序的目标。它只是使 JSON 成为 only 选项。如果您想将 JSON 设为默认并仍然支持所有其他类型,您可以执行以下操作:

    public static void Configure(HttpConfiguration config) {
        // move the JSON formatter to the front of the line
        var jsonFormatter = config.Formatters.JsonFormatter;
        config.Formatters.Remove(jsonFormatter);
        config.Formatters.Insert(0, jsonFormatter);
    }
    

    注意:JSON 是 Web API 2.0 的默认格式化程序。

    【讨论】:

    • 为我工作。好多了。
    猜你喜欢
    • 2014-03-30
    • 2013-03-21
    • 1970-01-01
    • 1970-01-01
    • 2013-09-21
    • 2017-03-10
    • 2018-10-01
    • 1970-01-01
    • 2017-09-05
    相关资源
    最近更新 更多