如何让 Web API 统一回传格式以及例外处理

如题所述

在使用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,而且可以马上返回。

通过使用自定义的JsonContentNegotiator替换系统默认的DefaultContentNegotiator,很好的实现Web Api只返回Json的功能,而且没有额外的开销。
温馨提示:答案为网友推荐,仅供参考
相似回答