Skip to content

Instantly share code, notes, and snippets.

@johnnonolan
Created November 27, 2015 14:43
Show Gist options
  • Save johnnonolan/9d84631ebc5085448cd1 to your computer and use it in GitHub Desktop.
Save johnnonolan/9d84631ebc5085448cd1 to your computer and use it in GitHub Desktop.
Nancy Content Negotiation
using System;
using Nancy;
using Nancy.Hosting.Self;
using Nancy.Responses.Negotiation;
using System.Collections.Generic;
using Nancy.Responses;
using Nancy.Bootstrapper;
namespace negotiation
{
public class MyBootstrapper : DefaultNancyBootstrapper
{
protected override NancyInternalConfiguration InternalConfiguration
{
get
{
var processors = new[]
{
typeof(MyResponseProcessor)
};
return NancyInternalConfiguration.WithOverrides(x => x.ResponseProcessors = processors);
}
}
}
class MainClass
{
public static void Main (string[] args)
{
using (var host = new NancyHost(new Uri("http://localhost:1234")))
{
StaticConfiguration.DisableErrorTraces = false;
host.Start();
Console.WriteLine ("Hello from nancy");
Console.ReadLine();
}
}
}
public class MyRequestModel {}
public class MyModule : NancyModule
{
public MyModule ()
{
Get ["/"] = c => {
return Negotiate.WithModel(new MyRequestModel());
};
}
}
public class MyResponseProcessor : IResponseProcessor
{
private MediaRange MediaType = new MediaRange("application/vnd.blah.gnn.v1");
public IEnumerable<Tuple<string, MediaRange>> ExtensionMappings { get { yield break;}}
public ProcessorMatch CanProcess(MediaRange requestedMediaRange, dynamic model, NancyContext context)
{
var contentTypeResult = MediaType.MatchesWithParameters (requestedMediaRange) ? MatchResult.ExactMatch : MatchResult.NoMatch;
return new ProcessorMatch {
ModelResult = MatchResult.DontCare,
RequestedContentTypeResult = contentTypeResult
};
}
public Response Process(MediaRange requestedMediaRange, dynamic model, NancyContext context)
{
var myModel = new {Success = true};
return new JsonResponse (myModel, new DefaultJsonSerializer());
}
}
}
using NUnit.Framework;
using System;
using Nancy.Testing;
using Nancy;
using negotiation;
namespace neg.tests
{
[TestFixture]
public class Test
{
[Test]
public void TestCase ()
{
StaticConfiguration.DisableErrorTraces = false; //so that we can see stack trace, etc in the response if there is an exception
var browser = new Browser(new MyBootstrapper(), d => d.Accept("application/vnd.blah.gnn.v1+json"));
var result = browser.Get("/", with => {
with.HttpRequest(); });
Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment