Web Api 中返回JSON的正确做法
在使用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/
Web Api 中返回JSON的正确做法的更多相关文章
- Web Api 中返回JSON的正确做法(转)
出处:http://www.cnblogs.com/acles/archive/2013/06/21/3147667.html 在使用Web Api的时候,有时候只想返回JSON:实现这一功能有多种方 ...
- 【ASP.NET Web API教程】6.2 ASP.NET Web API中的JSON和XML序列化
谨以此文感谢关注此系列文章的园友!前段时间本以为此系列文章已没多少人关注,而不打算继续下去了.因为文章贴出来之后,看的人似乎不多,也很少有人对这些文章发表评论,而且几乎无人给予“推荐”.但前几天有人询 ...
- Asp.Net Web API 2第十三课——ASP.NET Web API中的JSON和XML序列化
前言 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnblogs.com/aehyok/p/3446289.html 本文描述ASP.NET W ...
- ASP.NET Web API中的JSON和XML序列化
ASP.NET Web API中的JSON和XML序列化 前言 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnblogs.com/aehyok ...
- ASP.NET Web API 2 返回 Json格式
最近在学习ASP.NET的Web API,刚刚开始以为会有些复杂,结果却非常简单. 学习的地址:http://www.asp.net/web-api/overview/getting-started- ...
- Rest Web Api Controller 返回JSON格式大小写
public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Ro ...
- Web API中的返回值类型
WebApi中的返回值类型大致可分为四种: Void/ IHttpActionResult/ HttpResponseMessage /自定义类型 一.Void void申明方法没有返回值,执行成功后 ...
- ASP.NET Web API 中的返回数据格式以及依赖注入
本篇涉及ASP.NET Web API中的返回数据合适和依赖注入. 获取数据 public IEnumerable<Food> Get() { var results = reop.Get ...
- 能省则省:在ASP.NET Web API中通过HTTP Headers返回数据
对于一些返回数据非常简单的 Web API,比如我们今天遇到的“返回指定用户的未读站内短消息数”,返回数据就是一个数字,如果通过 http response body 返回数据,显得有些奢侈.何不直接 ...
随机推荐
- leetcode 168
168. Excel Sheet Column Title Given a positive integer, return its corresponding column title as app ...
- 第五百八十二天 how can I 坚持
好吧,是我错了,昨天,做好自己就行了,别人怎么样是别人的事,永远保持一颗单纯向上的心. 时间过得真快,明天又周六了.. 睡觉.
- CentOS和Ubuntu下安装配置Greenplum数据库集群(包括安装包和源码编译安装)
首先说一下,无论是CentOS/RedHat还是Ubuntu都可以按源码方式.安装包方式编译安装. 1. 规划 192.168.4.93(h93) 1个主master 2个主segm ...
- sqoop job 踩过的坑
sqoop 执行可以以job形式 也可以执行用命令执行,再用sqoopjob时,踩了几个坑,分享一下 1.服务器重启 由于服务器增加硬盘,需要重启后,发现sqoop job 无法执行,报连接数据库IO ...
- 自定义控件EditText
public class defineEditText extends EditText { Context context; Drawable d; public defineEditText(Co ...
- 【227】◀▶ IDL 其他常用函数
参考:Programming and Control Routines —— 编程和控制函数 01 N_ELEMENTS 表达式或者变量的元素个数. 02 DEFSYSV 定义系统变量. 03 ...
- nagios二次开发(二)---nagios和nagiosql合并与取舍
NAGIOS做前台 上一篇本人分析了nagios和nagiosql的优缺点,根据之前的使用经验及探索.决定将nagios做为监控数据的展示层,暂称做“前台”.将nagiosql做为监控体的配置层,暂称 ...
- VC++ 动态创建单个工具条,并加载外部的位图(bmp)文件为工具栏图像
步骤: 1, 在框架类CMainFrame头文件里,增加图像变量和工具条变量. CMFCToolBarImages m_UserImages; CMFCToolBar m_wndToolBar; 2, ...
- 快考试了,尽快写完HashTable。
(1)Count Primes 质数(素数):在大于1 的自然数中,除了1和它本身之外,不能被任何其他整数整除. 解题思路:使用一个boolean类型的数组,从i(2) 开始循环,将小于N的i的倍数都 ...
- signtool.exe not found
When check the [sign the Xap File] checkbox, build project failed due to signtool.exe not found. Fol ...