如何强制的ASP.NET Web API总是返回JSON? [英] How to force ASP.NET Web API to always return JSON?
本文介绍了如何强制的ASP.NET Web API总是返回JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
的ASP.NET Web API的默认操作内容协商 - 将返回XML或JSON或根据接受
头其它类型。我并不需要/想这一点,是有办法(如属性或东西)来告诉网页API总是返回JSON?
ASP.NET Web API does content negotiation by default - will return XML or JSON or other type based on the Accept
header. I don't need / want this, is there a way (like an attribute or something) to tell Web API to always return JSON?
推荐答案
<一个href=\"http://www.strathweb.com/2013/06/supporting-only-json-in-asp-net-web-api-the-right-way/\">Supporting只有在JSON的ASP.NET Web API - 的正确方法
替换IContentNegotiator与JsonContentNegotiator:
Replace IContentNegotiator with JsonContentNegotiator:
var jsonFormatter = new JsonMediaTypeFormatter();
//optional: set serializer settings here
config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
JsonContentNegotiator实现:
JsonContentNegotiator implementation:
public class JsonContentNegotiator : IContentNegotiator
{
private readonly JsonMediaTypeFormatter _jsonFormatter;
public JsonContentNegotiator(JsonMediaTypeFormatter formatter)
{
_jsonFormatter = formatter;
}
public ContentNegotiationResult Negotiate(
Type type,
HttpRequestMessage request,
IEnumerable<MediaTypeFormatter> formatters)
{
return new ContentNegotiationResult(
_jsonFormatter,
new MediaTypeHeaderValue("application/json"));
}
}
这篇关于如何强制的ASP.NET Web API总是返回JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文