在使用Web Api的时候,有时候只想返回JSON
最好的方法是使用自定义的只返回Json Result的content negotiation代替Web Api中默认的content negotiation。
Conneg通过实现IContentNegotiator的Negotiator方法实现扩展。Negotiator方法返回ContentNegotiationResult(它包装了你选择的headers和formatter)。
下面的方法通过传递一个JsonMediaTypeFormatter给自定义的conneg negotiator,让它一直返回applicaton/json 的content-type以及JsonMediaTypeFormatter。这种方法避免了每次请求都要重新创建一次formatter。
代码如下:in webApi config new class

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实例上注册你的新的实现机制:
public class WebApiConfig
{
public static void Register(HttpConfiguration config, IAppBuilder appBuilder)
{
//////////////////////////////
//Return json with lower case first letter of property names
var jsonFormatter = new JsonMediaTypeFormatter();
config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
appBuilder.UseWebApi(config);
}
}
通过替换默认的DefaultContentNegotiator,我们使用我们自定义的JsonContentNegotiator,它只支持Json,而且可以马上返回。
如果你想更深入的了解Content Negotiation的知识,你可以查看作者的这篇文章。
总结
通过使用自定义的JsonContentNegotiator替换系统默认的DefaultContentNegotiator,很好的实现Web Api只返回Json的功能,而且没有额外的开销。
本文介绍了如何在Web API中通过自定义内容协商(Content Negotiation)策略,确保仅返回JSON格式的数据,并使用驼峰式命名。通过实现IContentNegotiator并注册自定义的JsonMediaTypeFormatter,避免每次请求时重复创建formatter,降低了性能开销。
530

被折叠的 条评论
为什么被折叠?



