• Web Api 中返回JSON的正确做法(转)


    出处:http://www.cnblogs.com/acles/archive/2013/06/21/3147667.html

    在使用Web Api的时候,有时候只想返回JSON;实现这一功能有多种方法,本文提供两种方式,一种传统的,一种作者认为是正确的方法。

    JSON in Web API – the formatter based approach

    只支持JSON最普遍的做法是:首先清除其他所有的formatters,然后只保留JsonMediaTypeFormatter。

    有了HttpConfiguration的实例,你将会很简单的清除所有formatters,然后重新添加JsonMediaTypeFormatter。

    实现代码如下:

    configuration.Formatters.Clear();
    configuration.Formatters.Add(new JsonMediaTypeFormatter());

    这种方式虽然可以实现功能,但是所有的conent negotiation还是会发生,这就会产生以下额外的开销了。因为,你已经知道要返回的结果了,也只想返回Json,其他的content negotiation都不需要了。

    下面的方法可以很好的解决这个问题。

     

    JSON in Web API – the conneg based approach

    最好的方法是使用自定义的只返回Json Result的content negotiation代替Web Api中默认的content negotiation。

    Conneg通过实现IContentNegotiator的Negotiator方法实现扩展。Negotiator方法返回ContentNegotiationResult(它包装了你选择的headers和formatter)。

    下面的方法通过传递一个JsonMediaTypeFormatter给自定义的conneg negotiator,让它一直返回applicaton/json 的content-type以及JsonMediaTypeFormatter。这种方法避免了每次请求都要重新创建一次formatter。

    代码如下:

    复制代码
    public class JsonContentNegotiator : IContentNegotiator
    {
        private readonly JsonMediaTypeFormatter _jsonFormatter;
    
        public JsonContentNegotiator(JsonMediaTypeFormatter formatter) 
        {
            _jsonFormatter = formatter;    
        }
    
        public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
        {
            var result = new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json"));
            return result;
        }
    }
    复制代码

    接下来,你需要在HttpConfiguration实例上注册你的新的实现机制:

     

    var jsonFormatter = new JsonMediaTypeFormatter();
    //optional: set serializer settings here
    config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));

     

    通过替换默认的DefaultContentNegotiator,我们使用我们自定义的JsonContentNegotiator,它只支持Json,而且可以马上返回。

    如果你想更深入的了解Content Negotiation的知识,你可以查看作者的这篇文章

    总结

    通过使用自定义的JsonContentNegotiator替换系统默认的DefaultContentNegotiator,很好的实现Web Api只返回Json的功能,而且没有额外的开销。

     

     

    原文地址:http://www.strathweb.com/2013/06/supporting-only-json-in-asp-net-web-api-the-right-way/

     

    作者对Content Negotiation的讲解:http://www.strathweb.com/2012/07/everything-you-want-to-know-about-asp-net-web-api-content-negotation/

  • 相关阅读:
    异步编程
    写代码写至最有面向对象味道
    GitHub上整理
    用CQRS+ES实现DDD
    前端开发
    让低版本的IE浏览器 强制渲染为IE8 或者 以上 浏览器模式
    NHibernate系列
    hadoop搭建开发环境及编写Hello World
    Linux date -s(转)
    即时编译和打包您的 Groovy 脚本(转)
  • 原文地址:https://www.cnblogs.com/smileberry/p/6781410.html
Copyright © 2020-2023  润新知