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 ?
source share