Type is not specified

I have a Web API project that returns some product data.

If no Accept header is specified it returns XML as default, done like so in my WebApiConfig :

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

So default is XML, the first formatter, but the API still supports JSON if the request asks for it.

In my ControllerHelper , I added a 415 Format not supported response:

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

And I would like to throw that response if no Accept header is specified and therefore require it to be set, either to application/xml , text/xml or application/json .

For example, if I test to set accept in Advanced Rest Client to application/foo I want to throw an exception.


在这里输入图像描述


How to do this? Thanks in advance!


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);
    }
}

In your WebApiConfig file:

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

The code is from: http://pedroreys.com/2012/02/17/extending-asp-net-web-api-content-negotiation/

链接地址: http://www.djcxy.com/p/20404.html

上一篇: ASP.NET WebAPI OData 406

下一篇: 类型未指定