未指定Content-Type时抛出异常

时间:2014-09-04 08:51:38

标签: c# xml asp.net-mvc asp.net-web-api

我有一个Web API项目,它返回一些产品数据。

如果没有指定Accept标头,则默认返回XML,在我的WebApiConfig中这样做:

config.Formatters.Clear();
config.Formatters.Add(new XmlMediaTypeFormatter());
config.Formatters.Add(new JsonMediaTypeFormatter());
config.Formatters.Add(new FormUrlEncodedMediaTypeFormatter());

所以默认是XML,第一个格式化程序,但如果请求要求,API仍然支持JSON。

在我的ControllerHelper中,我添加了 415格式不支持响应:

catch (FormatException) 
{
    var resp = new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType) 
    {
        Content = new StringContent(string.Format(HttpStatusCode.UnsupportedMediaType.ToString())),
    };
    throw new HttpResponseException(resp);
}

如果未指定Accept标头,我想抛出该响应,因此需要将其设置为application/xmltext/xmlapplication/json

例如,如果我测试将Advanced Rest Client中的accept设置为application/foo我想抛出异常。


enter image description here


怎么做?提前谢谢!

1 个答案:

答案 0 :(得分:2)

public class NotAcceptableConnegHandler : DelegatingHandler
{
    private const string allMediaTypesRange = "*/*";

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var acceptHeader = request.Headers.Accept;
        if (!acceptHeader.Any(x => x.MediaType == allMediaTypesRange))
        {
            var hasFormetterForRequestedMediaType = GlobalConfiguration
                .Configuration
                .Formatters
                .Any(formatter => acceptHeader.Any(mediaType => formatter.SupportedMediaTypes.Contains(mediaType)));

            if (!hasFormetterForRequestedMediaType)
                return Task<HttpResponseMessage>.Factory.StartNew(() => new HttpResponseMessage(HttpStatusCode.NotAcceptable));
        }
        return base.SendAsync(request, cancellationToken);
    }
}

在您的WebApiConfig文件中:

public static void Register(HttpConfiguration config)
{
    config.MessageHandlers.Add(new NotAcceptableConnegHandler());
}

代码来自:http://pedroreys.com/2012/02/17/extending-asp-net-web-api-content-negotiation/