Change the default Content-Type value for responses in NancyFx

I am writing a REST API with NancyFx. I often got the code like this:

Post["/something"] = _ => { // ... some code if (success) return HttpStatusCode.OK; else return someErrorObject; }; 

The client always accepts application/json as the content type of all responses. In fact, it sets Accept: application/json in the request. Responses without application/json are errors regardless of the actual body. It just checks the content type and aborts it if it doesn't match json. I cannot change this behavior.

Now I am facing the problem that by simply returning HttpStatusCode.OK Nancy sets Content-Type: text/html , but as said, the client accepts the / json application and fails with an error, even the body is empty.

I managed to force the content type as follows:

 return Negotiate .WithContentType("application/json") .WithStatusCode(HttpStatusCode.OK); 

I do not want to repeat this code everywhere. Of course, I could abstract this in one function, but I'm looking for a more elegant solution.

Is there a way to override the Content-Type respones type so that return HttpStatusCode.OK sets my Content-Type to application/json ?

+4
source share
1 answer

Based on the assumption that you want to return all responses as JSON, you will need a custom loader. You can improve this if you want using insertion rather than cleaning up response processors, so you can return to using an XML processor, etc.

This will automatically catch Nancy in the way that no additional setup is required.

 public class Bootstrap : DefaultNancyBootstrapper { protected override NancyInternalConfiguration InternalConfiguration { get { return NancyInternalConfiguration.WithOverrides( (c) => { c.ResponseProcessors.Clear(); c.ResponseProcessors.Add(typeof(JsonProcessor)); }); } } } 
+6
source

All Articles