Search code examples
javascriptjquerynancy

Returning a Json file with Nancy for use in Jquery


I have a file that contains some JSON with an extension of .json. I am using Nancy to serve the file as follows:

Get["/schema/{file}"] = parameters =>
{
    return Response.AsFile(Directory.GetCurrentDirectory() + @"\sitefiles\schema\" + parameters.file as String);
}

When I make a jQuery ajax request for the file like this:

$.ajax({
            url: "/schema/auditResponseSchema.json",
            type: 'GET',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            cache: false,
            success: function (responseSchema) {
                console.log("get response data - Success");
                console.log(responseSchema);
            },
            timeout: 5000,
            error: function (xmlObj, textStatus, errorThrown) {
                console.log("get response data - failed. status:" + textStatus + " error:" + errorThrown);
            }
        });

I get the file back but it is not recognised as JSON, I'm sure this is because of the Content-Type being returned is application/octet-stream.

How do i change the to Content-Type to be application/json?

I've tried:

// this returns "application/json in the content.
return Response.AsFile(Directory.GetCurrentDirectory() + @"\sitefiles\schema\" + parameters.file as String).Headers["Content-Type"] = "application/json";

// this returns the location of the file
return Response.AsJson(Directory.GetCurrentDirectory() + @"\sitefiles\schema\" + parameters.file as String);

Do i have to read the contents of the file into a string and then use Response.AsJson or is there a way to change the headers the Response.AsFile returns?


Solution

  • Currently you can't override the content type using the extension method, you should be able to, and I'll log an issue and get it fixed for 0.8, but you currently can't.

    You can, however, just return a GenericFileResponse directly (which is all the extension method does behind the scenes):

    return new GenericFileResponse(Directory.GetCurrentDirectory() + @"\sitefiles\schema\" + parameters.file as String, "application/json");
    

    I'd recommend against using Directory.GetCurrentDirectory though, you should be able to just specify it as a relative path.

    Edit: logged the issue here if you're interested https://github.com/NancyFx/Nancy/issues/315

    Edit: and it's fixed .. the fix will be in 0.8 coming at the end of the week :-)