1

我有一个文件,其中包含一些扩展名为 .json 的 JSON。我正在使用 Nancy 来提供文件,如下所示:

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

当我对这样的文件发出 jQuery ajax 请求时:

$.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);
            }
        });

我取回了文件,但它不被识别为 JSON,我确定这是因为返回的 Content-Type 是 application/octet-stream。

如何将 Content-Type 更改为 application/json?

我试过了:

// 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);

我必须将文件的内容读入字符串然后使用 Response.AsJson 还是有办法更改 Response.AsFile 返回的标题?

4

2 回答 2

3

目前你不能使用扩展方法覆盖内容类型,你应该可以,我会记录一个问题并将其修复为 0.8,但你目前不能。

但是,您可以直接返回一个 GenericFileResponse (这是扩展方法在幕后所做的所有事情):

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

我建议不要使用 Directory.GetCurrentDirectory 虽然,您应该能够将其指定为相对路径。

编辑:如果您有兴趣,请在此处记录问题https://github.com/NancyFx/Nancy/issues/315

编辑:它已修复..修复将在本周末发布 0.8 :-)

于 2011-09-28T11:20:49.963 回答
2

这是修复https://github.com/NancyFx/Nancy/commit/3d3e45017c0710f4732cf971274f9116611ec478现在在 master :)

于 2011-09-28T12:29:42.327 回答