想要允许从不同的站点访问我的API。对此有:
services
.AddCors(options =>
{
options.AddPolicy(PolicyName, builder =>
{
builder
.SetIsOriginAllowedToAllowWildcardSubdomains()
.WithOrigins(
"http://*.my-api.com",
"http://*.my-api.service"
)
...
这似乎不允许httpS或我在请求中指定端口。
例如:https://www.my-api.com:3000
思想可以用SetIsOriginAllowed()替换WithOrigins
services
.AddCors(options =>
{
options.AddPolicy(PolicyName, builder =>
{
builder
.SetIsOriginAllowed(IsOriginAllowed)
其中IsOriginAllowed函数定义为:
private static bool IsOriginAllowed(string host)
{
var corsOriginAllowed = new[] { "my-api.com", "my-api.service" };
return corsOriginAllowed.Any(origin =>
Regex.IsMatch(host, $@"^http(s)?://.*{origin}(:[0-9]+)?$", RegexOptions.IgnoreCase));
}
但这根本不起作用,即使正则表达式在我想要时也会返回true。
有谁知道为什么这不起作用,可以告诉我允许httpS的正确方法(除了用httpS和不同的端口复制WithOrigins()中的所有域。
谢谢
SetIsOriginAllowed()确实有效。正在使用Postman进行测试,并且正如所述,Postman并不关心从服务器返回的标头。它是强制执行Cors标头的浏览器。
使用下面的javascript测试在测试站点下正确创建一个小的html页面
<html>
<script>
fetch('http://test.com:5000/v2/campaign/hallo3').then(function(response) {
return response.json();
}).then(function(j) {
alert(JSON.stringify(j));
});
</script>
</html>
当域未包含在Cors允许列表浏览器中时,不会显示API返回的值
将测试域添加到允许的域列表浏览器后显示数据并获取内容Cors头
另一个问题是只有SetIsOriginAllowed()服务器没有发送'Vary'标头。不得不同时设置:
.SetIsOriginAllowed(IsOriginAllowed)
.WithOrigins(corsOriginAllowed)