Nancy converts (404) JsonResponse to Html one

I have a Nancy Fx app that acts as a pure API endpoint (app / json only, no text / html or browser, etc.) and a module that comes back for example. following:

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

      

However, I noticed one quirk - a client that has an Accept-Header set to "application / json" and making a GET request here, return a text / html response, even worse in the case of .NotFound a Nancy -specific / own 404 error, in case of .OK an exception is thrown due to missing Views.

What makes me even weirder to me is that inside my custom IStatusCodeHandler I "see" that context.Response is a JsonResponse, somewhere along the pipeline, which is processed and (as needed) further converted to text / html somehow though, and I'm wondering why.

Is there a way to prevent conversion to text / html?

+3


source to share


1 answer


This is due to what Nancy has DefaultStatusCodeHandler

, which handles responses 500

and 404

. This is the last thing running in Nancy's pipeline before the host accepts a response.

What you see is because the handler receives a response 404

(albeit JsonResponse

) and it cannot know if hard (the route just doesn't exist) or soft (a route but returned 404

) status code, so it converts it to 404

default page . You might argue that you need to check the accept header first, but this is not the case right now.



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

in your loader:

protected override NancyInternalConfiguration InternalConfiguration
{
    get
    {
        return NancyInternalConfiguration
            .WithOverrides(config => config.StatusCodeHandlers.Clear());
    }
}

      

+4


source







All Articles