gpt4 book ai didi

asp.net-core - .Net 核心 CORS - SetIsOriginAllowed 如何工作?

转载 作者:行者123 更新时间:2023-12-04 11:55:33 70 4
gpt4 key购买 nike

希望允许从不同站点访问我的 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));
}

但这根本不起作用,即使正则表达式在我想要的时候也返回真。

有谁知道为什么这不起作用,并且可以向我展示允许 httpS 的正确方法(除了使用 httpS 和不同端口复制 WithOrigins() 中的所有域。

谢谢

最佳答案

SetIsOriginAllowed() 确实有效。正在使用 Postman 进行测试,并且正如有人所说,Postman 不关心从服务器返回的 header 。是浏览器强制执行 Cors header 。

使用以下 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 的返回值

Domain not allowed

将测试域添加到允许域列表浏览器后显示数据并获取内容 Cors header

enter image description here

另一个问题是,只有 SetIsOriginAllowed() 服务器没有发送“Vary” header 。必须同时设置:
.SetIsOriginAllowed(IsOriginAllowed)
.WithOrigins(corsOriginAllowed)

关于asp.net-core - .Net 核心 CORS - SetIsOriginAllowed 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47837077/

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