【发布时间】:2022-11-11 00:07:13
【问题描述】:
我有一个 API,从面向公众的网站调用一个端点。每当网站调用 API 时,我都会收到以下错误
Access to fetch at '{{API Endpoint}}' from origin 'https://{{Website Domain}}' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values 'https://{{Website Domain}}, *', but only one is allowed. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
我的 API 的 Program.cs 似乎设置正确
builder.Services.AddCors(options =>
{
options.AddPolicy(
"CMSPolicy",
policy =>
{
policy.WithOrigins("https://{{Website Domain}})
.WithHeaders(HeaderNames.ContentType, "application/json");
});
});
app.UseCors();
我的控制器在端点上有 [EnableCors("CMSPolicy")] 注释。
这以前是可行的,但是已经进行了更改,API 现在导入了一个定制的 NuGet 包,该包本身包含一些控制器。这些导入的控制器与受影响的控制器无关,并且定制包不包含我可以看到的任何引用 CORS 的代码,但为了完整性,我将包含此信息以防相关。
如果我从我的端点中删除 EnableCors 注释,那么来自网站的调用可以工作,但那是 Access-Control-Allow-Origin 标头值为“*”,我希望这个标头的安全性只是我的网站域
【问题讨论】:
-
目前
policy.WithOrigins(...行中似乎有一个开/关引号不匹配 -
这只是我在取出实际域名时的错误 - 在代码中很好
标签: c# asp.net-core cors asp.net-core-6.0