Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic Content Negotation When Assigning To Response

Tags:

c#

nancy

How can I take advantage of the content negotiation pipeline when assigning to NancyContext.Response?

Currently my IStatusCodeHandler.Handle method returns JSON regardless of any content negotiation.

I want this method to use JSON or XML according on any content negotiation (preferably using the content negotiation pipeline.)

public void Handle(HttpStatusCode statusCode, NancyContext context)
{
    var error = new { StatusCode = statusCode, Message = "Not Found" };
    context.Response =
        new JsonResponse(error, new JsonNetSerializer())
            .WithStatusCode(statusCode);
}
like image 297
Caster Troy Avatar asked Sep 30 '22 15:09

Caster Troy


1 Answers

In the default Nancy engine, the status code handlers are invoked after content negotiation has already taken place. If you're using version 0.23 or newer, the content negotiation parts have been pulled out into a separate service and can be used anywhere, at any time, just given a model and the context. Using this service, the IResponseNegotiator, you should be able to renegotiate using the error model.

Something like this:

public class MyStatusCodeHandler : IStatusCodeHandler
{
    private readonly IResponseNegotiator _negotiator;

    public MyStatusCodeHandler(IResponseNegotiator negotiator)
    {
        _negotiator = negotiator;
    }

    public bool HandlesStatusCode(HttpStatusCode statusCode, NancyContext context)
    {
        return statusCode == HttpStatusCode.NotFound;
    }

    public void Handle(HttpStatusCode statusCode, NancyContext context)
    {
        var error = new { StatusCode = statusCode, Message = "Not Found" };
        context.Response = _negotiator.NegotiateResponse(error, context);
    }
}
like image 166
khellang Avatar answered Oct 04 '22 18:10

khellang