Created
February 28, 2012 12:17
-
-
Save codeprogression/1932196 to your computer and use it in GitHub Desktop.
Nancy pipeline handler for content negotiation
This file contains 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
public class ContentNegotiationPipelineItem : PipelineItem<Action<NancyContext>> | |
{ | |
public ContentNegotiationPipelineItem() | |
: base("Content Negotiation", action) | |
{ | |
} | |
static readonly Action<NancyContext> action = ctx => | |
{ | |
var request = ctx.Request; | |
if (request == null || request.Headers == null || request.Headers.Accept == null) | |
return; | |
if (!ctx.Items.ContainsKey("Content-Negotiation")) return; | |
var responses = (List<Response>)ctx.Items["Content-Negotiation"]; | |
if (responses == null) return; | |
responses.Insert(0, new Response | |
{ | |
Contents = ctx.Response.Contents, | |
ContentType = ctx.Response.ContentType, | |
Headers = ctx.Response.Headers, | |
StatusCode = ctx.Response.StatusCode | |
}); | |
foreach (var cookie in ctx.Response.Cookies) | |
responses[0].AddCookie(cookie); | |
foreach (var contentType in request.Headers.Accept.Select(x => x.Item1)) | |
{ | |
var indexOf = contentType.IndexOf("/", StringComparison.Ordinal); | |
if (contentType == "*/*") | |
return; | |
var response = contentType.EndsWith("/*") | |
? responses.FirstOrDefault( | |
x => x.ContentType.StartsWith(contentType.Substring(0, indexOf))) | |
: responses.FirstOrDefault(x => x.ContentType == contentType); | |
if (response != null) | |
{ | |
ctx.Response = response; | |
break; | |
} | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment