-
-
Save DmitryMak/2499672 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); | |
} | |
// 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