如何从 Internet Explorer 向 Asp.Net Core API 发送 GET 请求?

How to send GET request from internet explorer to Asp.Net Core API?

我正在开发 Asp.Net Core 3.1 API,当我从 google chrome、Edge、Postman 发送 GET 请求时,一切都按预期工作。但是当我从 Internet Explorer 发送 GET 请求时,它开始下载一个文件 default.json,其内容作为 GET 请求的响应。

默认操作方法:

public IEnumerable<string> Get()
{
    return new string[] { "Welcome" };
}

default.json内容:

[
    "Welcome"
]

我在互联网上搜索但没有找到任何有用的东西。

FVI,当我使用 visual studio 运行 API 或使用 IIS 在服务器上部署 API 时,我有相同的观察结果。

IE版本:11.900.18362.0

所以我要提问了。

  1. IE不支持吗,这是IE的默认行为吗?
  2. 如果是,那么如何解决?

这是 IE 的默认行为,归结为它不知道如何处理 */json 等 mime 类型的内容,因此建议下载。

假设这是针对一般用户的,而您只想在浏览器中显示 json 数据,您可以将内容服务器端转换为文本。

public ContentResult Get()
{
    var jsondata = new string[] { "Welcome" };
    return Content(JsonSerializer.Serialize(jsondata));
}

如果你打算对实际的 json 数据做一些事情,通常在使用 api 时,你将使用某种客户端脚本(例如 Ajax 如下面的示例或类似的)来获取内容,在那些情况下不会有任何问题,就像您遇到的那样。

var xhr = new XMLHttpRequest();
xhr.open('GET', '/api/your-method', true);
xhr.onload = function (e) {
    if (this.status == 200) {
        var jsonstring = this.responseText;
        // do something with the json string, e.g. JSON.parse(jsonstring)
    }
};
xhr.send();

这里有几篇建议更改注册表的帖子,但它们不可行,除非它适用于您自己的本地计算机 (如果适用,选择开箱即用的浏览器一定更容易).

  • Display JSON in IE as HTML Without Download
  • How can I convince IE to simply display application/json rather than offer to download it?

编辑

如评论中所建议,另一种选择是显式更改 MIME 类型:

  • Json response download in IE(7~10)