Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override the default Content-Type for responses in NancyFx

Tags:

c#

nancy

I'm writing a REST API with NancyFx. I often got code like this:

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

The client always assumes application/json as the content type of all responses. It actually sets Accept: application/json in the request. Responses without application/json are errors regardless of the actual body. It simply checks the content type and aborts if it doesn't match json. I can't change this behaviour.

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

I was able to force the content type like this:

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

I don't want to repeat this code everywhere. Of course I could abstract that in a single function but I'm looking for a more elegant solution.

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

like image 966
MBulli Avatar asked Mar 15 '23 04:03

MBulli


1 Answers

Based on the assumption of wanting to return all responses as JSON you will need a custom bootstrapper. You can enhance this further if you like by using an insert as opposed to clearing the response processors thus the fallback of using the XML processor etc is possible.

This will get automatically picked up by Nancy by the way no additional configuration required.

public class Bootstrap : DefaultNancyBootstrapper
{
    protected override NancyInternalConfiguration InternalConfiguration
    {
        get
        {
            return NancyInternalConfiguration.WithOverrides(
                (c) =>
                {
                    c.ResponseProcessors.Clear();
                    c.ResponseProcessors.Add(typeof(JsonProcessor));
                });
        }
    }
}
like image 65
Dr Schizo Avatar answered Apr 09 '23 21:04

Dr Schizo