Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nancy transforms a (404) JsonResponse to Html one

Tags:

nancy

I have a Nancy Fx application that acts as a pure API endpoint (application/json only, no text/html or browser etc access intended) and a module that returns e.g. the following:

return
    userExists
        ? Negotiate.WithStatusCode(HttpStatusCode.OK)
        : Negotiate.WithStatusCode(HttpStatusCode.NotFound);

However, I noticed one particularity - client's that have an Accept-Header set to 'application/json' and perform a GET request here, do get a text/html response back, even worse - in the .NotFound case a Nancy-specific/own 404 error is returned, in case of .OK an exception occurs due to missing Views.

What makes it even stranger for me is that inside my custom IStatusCodeHandler I "see" that the context.Response is a JsonResponse, somewhere down the pipeline this gets handled and (attempted to be) transformed further to text/html somehow though, and I wonder why.

Is there any way I can prevent the transformation to text/html?


1 Answers

This is because Nancy has a DefaultStatusCodeHandler that handles 500 and 404 responses. It's the last thing that runs in the Nancy pipeline before the host takes over the response.

What you're seeing is because the handler gets a 404 response (albeit a JsonResponse), and it can't know whether it's a hard (a route simply didn't exist) or a soft (a route existed but returned 404) status code, so it transforms it to the default 404 page. You might argue that it should check the accept header before doing so, but right now it isn't.

If you don't want this behavior, you can remove the default status code handler by overriding the InternalConfiguration property in your bootstrapper:

protected override NancyInternalConfiguration InternalConfiguration
{
    get
    {
        return NancyInternalConfiguration
            .WithOverrides(config => config.StatusCodeHandlers.Clear());
    }
}
like image 65
khellang Avatar answered Mar 10 '26 14:03

khellang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!