如何强制 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 默认进行内容协商 - 将根据 Accept
标头返回 XML 或 JSON 或其他类型.我不需要/想要这个,有没有办法(比如属性或其他东西)告诉 Web 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?
推荐答案
在 ASP.NET Web API 中仅支持 JSON – 正确的方法
用 JsonContentNegotiator 替换 IContentNegotiator:
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屋!
查看全文