-
-
Save lukemcgregor/2991443 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Based on code from: | |
/// http://pedroreys.com/2012/02/17/extending-asp-net-web-api-content-negotiation/ | |
/// </summary> | |
public class NotAcceptableConnegHandler : DelegatingHandler { | |
private readonly HttpConfiguration _configuration; | |
public NotAcceptableConnegHandler(HttpConfiguration configuration) { | |
if (configuration == null) { | |
throw new ArgumentNullException("configuration"); | |
} | |
_configuration = configuration; | |
} | |
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { | |
var acceptHeader = request.Headers.Accept; | |
// from RFC: | |
// If no Accept header field is present, then it is assumed that the client accepts all media types. | |
if (!acceptHeader.Any()) { | |
return base.SendAsync(request, cancellationToken); | |
} | |
var hasFormatterForRequestedMediaType = _configuration | |
.Formatters | |
.Any(formatter => acceptHeader.Any(mediaType => formatter.SupportedMediaTypes.Contains(mediaType) | |
|| formatter.MediaTypeMappings.Any(m=> m.TryMatchMediaType(request) > 0))); | |
if (!hasFormatterForRequestedMediaType) { | |
return Task<HttpResponseMessage>.Factory.StartNew(() => new HttpResponseMessage(HttpStatusCode.NotAcceptable)); | |
} | |
return base.SendAsync(request, cancellationToken); | |
} | |
} |
Yeah ill put one through at some stage, really liked your article, totally
agree that 406 is the correct response if nothing matches the accept header
:)
…On 26 June 2012 09:44, Pedro Reys < ***@***.*** > wrote:
hey Luke, do you mind sending a pull request to the [contrib](https://github.com/WebApiContrib/WebAPIContrib)?
---
Reply to this email directly or view it on GitHub:
https://gist.github.com/2991443
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey @lukemcgregor, do you mind sending a pull request to the contrib?