gpt4 book ai didi

c# - Access-Control-Allow-Origin 在 header 请求 ASP.NET Web API 中出现两次

转载 作者:太空宇宙 更新时间:2023-11-03 14:59:11 25 4
gpt4 key购买 nike

我的 ASP.NET Web API Controller 之一。我的客户端应用程序返回以下错误:

Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed. Origin 'http://localhost:8100' is therefore not allowed access.

我知道发生此错误是因为 header 包含多个值。当通过 Chrome 调用 API 时,我可以在“响应 header ”中看到它,它看起来像这样:

HTTP/1.1 200 OK

Cache-Control: no-cache

Content-Length: 0

Server: Microsoft-IIS/8.0

Access-Control-Allow-Methods: GET, POST

Access-Control-Allow-Origin: *

Access-Control-Allow-Headers: Content-Type, Accept, Pragma, Cache-Control, Authorization

Access-Control-Max-Age: 1728000

X-Powered-By: ASP.NET

Access-Control-Allow-Origin: *

Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE

Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization

Set-Cookie: ARRAffinity=ef9b3770b61f10f9696b0dedcb39a7f47a83c0e4d6cdbf367f3149482592ef06;Path=/;HttpOnly;Domain=seirse.azurewebsites.net

如您所见,它显然出现了两次。

我遇到的问题是,我启用 CORS 的唯一地方是通过我应用程序中的 web.config,例如

<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, DELETE" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, Authorization" />
</customHeaders>
</httpProtocol>

我已经 100% 确定我没有通过 Startup.cs 或在 Controller 中启用 CORS。

据我所知, Controller 没有任何异常:

// GET: api/Address/all
[HttpGet]
public AddressResultModel All()
{
try
{
var userId = _accountService.GetUserId(Request);
return _customerRepository.GetAddresses(userId);
}
catch (Exception)
{
return null;
}
}

知道问题出在哪里吗?

最佳答案

事实证明,我的 Global.asax.cs 中有代码,它正在为 OPTIONS HTTP 请求的响应添加 header 。

我添加此代码的原因是由于一个单独的问题,即我收到了针对 OPTIONS HTTP 请求的“405 Method Not Allowed”错误消息。

为了解决这两个问题,我删除了添加额外 header 的代码并将其缩减为:

protected void Application_BeginRequest()
{
if (Request.Headers.AllKeys.Contains("Origin", StringComparer.CurrentCultureIgnoreCase)
&& Request.HttpMethod == "OPTIONS")
{
Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Pragma, Cache-Control, Authorization ");
Response.End();
}
}

我不确定为什么这能解决问题。

关于c# - Access-Control-Allow-Origin 在 header 请求 ASP.NET Web API 中出现两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47102317/

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