为localhost上的任何端口启用CORS [英] Enable CORS for any port on localhost
问题描述
在asp.net核心中,我可以使用中间件在某些方法上启用CORS,例如
in asp.net core i can use middleware to enable CORS on certain methods as described here
我想知道是否有可能为localhost
上的任何方案和任何端口启用CORS(仅用于测试目的).我尝试使用通配符,但不起作用
i want to know if its possible to enable CORS for any scheme and any port on localhost
( for testing purpose only). i tried wildcard and it does not work
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
if(_environment.IsDevelopment())
{
options.AddDefaultPolicy(
builder =>
{
builder.WithOrigins("http://localhost/*",
"https://localhost/*");
});
});
}
else
{
options.AddDefaultPolicy(
builder =>
{
builder.WithOrigins("http://example.com",
"http://www.contoso.com");
});
});
}
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
推荐答案
ASP.NET Core's SetIsOriginAllowed
method gives you full control over whether or not an origin is allowed to participate in CORS. Here's an example based on your code sample:
if(_environment.IsDevelopment())
{
options.AddDefaultPolicy(builder =>
{
builder.SetIsOriginAllowed(origin => new Uri(origin).Host == "localhost");
});
}
else
{
// ...
}
传递给SetIsOriginAllowed
委托的origin
值是完整原点,看起来像http://localhost:8080
.使用 Uri
,代码上面比较了 Host
反对localhost
,最终允许所有localhost
起源.
The origin
value passed in to the SetIsOriginAllowed
delegate is the full origin, which looks something like http://localhost:8080
. Using Uri
, the code above compares the Host
against localhost
, which ends up allowing all localhost
origins.
这篇关于为localhost上的任何端口启用CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!