Automatically negotiate content when assigning a response

How can I use the content negotiation pipeline when assigning NancyContext.Response?

Currently, my method IStatusCodeHandler.Handlereturns JSON regardless of any content negotiation.

I want this method to use JSON or XML in accordance with any content negotiation (preferably using a 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);
}
+4
source share
1 answer

Nancy , . 0.23 , , . , IResponseNegotiator, .

- :

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);
    }
}
+4

Source: https://habr.com/ru/post/1543799/


All Articles