I have a NancyContext
and I need to get a Response
with a body based on the correct content negotiator for the request. I think I can use Nancy\'s
Based on your code sample, here's one possible way:
public Response ConvertToHttpResponse(Exception exception, NancyContext context, IEnumerable processors, Nancy.Conventions.AcceptHeaderCoercionConventions coercionConventions)
{
var negotiator = new Negotiator(context)
.WithStatusCode(HttpStatusCode.BadRequest)
.WithReasonPhrase(exception.Message);
return new DefaultResponseNegotiator(processors, coercionConventions)
.NegotiateResponse(negotiator, context);
}
Depending on your implementation, a better way may be to have processors
and coercionConventions
as parameters to the class constructor, and allow the IoC container to resolve them as normal. However, in my case, I resolved them in my bootstrapper, and gave them to an extension method I created for negotiating Exception
instances to an XML or JSON response.
protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
{
// Resolving outside the lambda because no more components will be registered at this point.
var responseProcessors = container.Resolve>();
var coercionConventions = container.Resolve();
pipelines.OnError += (context, exception) =>
{
return exception.GetErrorResponse(context, responseProcessors, coercionConventions);
};
}