我就是这样实现的:
我正在用
等原始
:
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddCors(options =>
{
options.AddPolicy(name: "AllowedCorsOrigins",
builder =>
{
builder
.SetIsOriginAllowed(IsOriginAllowed)
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
// ...
一如既往地激活Cors:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
// ...
app.UseCors("AllowedCorsOrigins");
// ...
这就是方法,应该能做到。
接受来自的所有请求example.com网站还有一个-example.com网站包括所有子域。
如果服务正在运行的ASPNETCORE_环境包含“DEV”,那么也允许localhost。
private static bool IsOriginAllowed(string origin)
{
var uri = new Uri(origin);
var env = System.Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "n/a";
var isAllowed = uri.Host.Equals("example.com", StringComparison.OrdinalIgnoreCase)
|| uri.Host.Equals("another-example.com", StringComparison.OrdinalIgnoreCase)
|| uri.Host.EndsWith(".example.com", StringComparison.OrdinalIgnoreCase)
|| uri.Host.EndsWith(".another-example.com", StringComparison.OrdinalIgnoreCase);
if (!isAllowed && env.Contains("DEV", StringComparison.OrdinalIgnoreCase))
isAllowed = uri.Host.Equals("localhost", StringComparison.OrdinalIgnoreCase);
return isAllowed;
}