gpt4 book ai didi

asp.net - 升级到 asp.net 5.2.3 后,CORS 不适用于 "*"源

转载 作者:行者123 更新时间:2023-12-03 03:08:20 25 4
gpt4 key购买 nike

我有一个使用 Web api 的项目和一个使用 asp.net mvc 的项目。它们是使用 CORS 模块配置的。

使用 Web Api 的项目配置为允许任何来源,因为它部署在 Azure 上并且是 OData 端点,因此我们不知道谁将使用它。

OData 端点配置

// inside configuration
config.EnableCors();

// controllers
[EnableCors(origins: "*", headers: "*", methods: "*")]
[Authorize]
[HttpPost]
public void ...

从我的 MVC 客户端,使用 Angular $http,我们使用承载 token 发出经过身份验证的请求,如下所示:

请求已发送

Request URL:http://myodata.com/Products
Request Method:GET
Status Code:200 OK
Remote Address:123.123.123.123

这是发送的 header

Host: myodata.com
Authorization: bearer 123-ABC
Origin: http://myclient.com
Content-Type: application/json;charset=UTF-8
Accept: application/json, text/plain, */*
Referer: http://myclient.com/

问题在于响应,正如您在此处看到的:

HTTP/1.1 200 OK
Access-Control-Allow-Origin: *

因为从 5.2.2 升级到 5.2.3 后,CORS 模块正在发送 Access-Control-Allow-Origin: *

很明显,我们从浏览器中收到此错误:

XMLHttpRequest cannot load http://myodata.com/Products. 
The value of the 'Access-Control-Allow-Origin' header
in the response must not be the wildcard '*'
when the request's credentials mode is 'include'.
Origin 'http://myclient.com' is therefore not allowed access.
The credentials mode of requests initiated by the XMLHttpRequest
is controlled by the withCredentials attribute.

但是调用实际上成功了,它在 Angular 端爆炸了。直到今天从 5.2.2 升级到 5.2.3 后才出现此问题

最佳答案

要尝试的一件事是使用 URL Rewrite Module 设置 header ,将以下内容添加到 %SystemDrive%\inetpub\wwwroot\ 中的 Web.configApplicationHost.config 文件中。

<configuration> 
<system.webServer>
<rewrite>
<outboundRules>
<rule name="Make Access-Control-Allow-Origin echo Origin">
<match serverVariable="RESPONSE_Access-Control-Allow-Origin"
pattern=".+" negate="true" />
<action type="Rewrite" value="{HTTP_ORIGIN}" />
</rule>
</outboundRules>
</rewrite>
</system.webServer>
</configuration>

如果上述方法不起作用,那么您可以尝试 CORS in IIS issue with credentials and wildcard in Access-Control-Allow-Origin 答案中的版本.

另一种方法:in the global.asax or other code for your service, add something like :

if (ValidateRequest()) {
Response.Headers.Remove("Access-Control-Allow-Origin");
Response.AddHeader("Access-Control-Allow-Origin", Request.Headers["origin"]);
Response.Headers.Remove("Access-Control-Allow-Credentials");
Response.AddHeader("Access-Control-Allow-Credentials", "true");
Response.Headers.Remove("Access-Control-Allow-Methods");
Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
}

...最重要的部分是:

Response.AddHeader("Access-Control-Allow-Origin", Request.Headers["origin"]);

无论哪种情况,最终效果都应该是:您的后端获取 Origin 请求 header 的值并将其作为 Access-Control-Allow-Origin 响应回显- header 值。

关于asp.net - 升级到 asp.net 5.2.3 后,CORS 不适用于 "*"源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42296323/

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