默认"接受" Asp.Net Web API的标头值

时间:2017-07-19 07:43:24

标签: asp.net asp.net-web-api http-accept-header

如果在Asp.Net Web API请求中省略Accept标头,服务器将返回(415) Unsupported Media Type

当我的请求在其标头中不包含application/json值时,我正在寻找一种强制API采用默认返回类型(在我的情况下为Accept)的方法。

经过大量的阅读和搜索,我不确定这是否可能?

2 个答案:

答案 0 :(得分:0)

这是内容协商者选择正确格式化程序来序列化响应对象的责任。但是默认情况下,如果找不到合适的格式化程序,WebApi框架会获得JsonFormatter

  

If there are still no matches, the content negotiator simply picks the first formatter that can serialize the type.

所以这是奇怪的行为。无论如何,如果请求没有JsonFormatter标题,您可以设置自定义内容协商器以选择显式Accept

public class JsonContentNegotiator : DefaultContentNegotiator
{
    protected override MediaTypeFormatterMatch MatchAcceptHeader(IEnumerable<MediaTypeWithQualityHeaderValue> sortedAcceptValues, MediaTypeFormatter formatter)
    {
        var defaultMatch = base.MatchAcceptHeader(sortedAcceptValues, formatter);

        if (defaultMatch == null)
        {
            //Check to find json formatter
            var jsonMediaType = formatter.SupportedMediaTypes.FirstOrDefault(h => h.MediaType == "application/json");
            if (jsonMediaType != null)
            {
                return new MediaTypeFormatterMatch(formatter, jsonMediaType, 1.0, MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderLiteral);
            }
        }

        return defaultMatch;
    }
}

并替换HttpConfiguration对象

config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator());

答案 1 :(得分:0)

您可以通过以下技巧强制框架在缺少HTTP Accept标头时使用XML格式器:

var jsonFormatter = config.Formatters.JsonFormatter;
config.Formatters.Remove(config.Formatters.JsonFormatter);
config.Formatters.Add(jsonFormatter);

这样,JSON格式器将成为列表中第二个注册的格式器,而XML将成为第一个。