{ r-6ren">
gpt4 book ai didi

javascript - 使用 Nancy 返回 Json 文件以在 Jquery 中使用

转载 作者:行者123 更新时间:2023-11-30 09:03:04 25 4
gpt4 key购买 nike

我有一个文件,其中包含一些扩展名为 .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 返回的 header ?

最佳答案

目前你不能使用扩展方法覆盖内容类型,你应该可以,我会记录一个问题并在 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 中发布:-)

关于javascript - 使用 Nancy 返回 Json 文件以在 Jquery 中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7582270/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com