Skip to content

Instantly share code, notes, and snippets.

@lukemcgregor
Forked from DmitryMak/gist:2499672
Created June 25, 2012 21:38
Show Gist options
  • Select an option

  • Save lukemcgregor/2991443 to your computer and use it in GitHub Desktop.

Select an option

Save lukemcgregor/2991443 to your computer and use it in GitHub Desktop.
/// <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);
}
}
@lukemcgregor
Copy link
Copy Markdown
Author

lukemcgregor commented Jun 25, 2012 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment