Skip to content

Instantly share code, notes, and snippets.

@DmitryMak
Forked from pedroreys/gist:1850200
Created April 26, 2012 13:38
Show Gist options
  • Save DmitryMak/2499672 to your computer and use it in GitHub Desktop.
Save DmitryMak/2499672 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);
}
// if client explicitly accepts all media types (*/*)
if (acceptHeader.Any(a => a.MediaType == "*/*" && a.Quality != 0.0)) {
return base.SendAsync(request, cancellationToken);
}
var hasFormatterForRequestedMediaType = _configuration
.Formatters
.Any(formatter => acceptHeader.Any(mediaType => formatter.SupportedMediaTypes.Contains(mediaType)));
if (!hasFormatterForRequestedMediaType) {
return Task<HttpResponseMessage>.Factory.StartNew(() => new HttpResponseMessage(HttpStatusCode.NotAcceptable));
}
return base.SendAsync(request, cancellationToken);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment