根据MS文档,我需要为我的Web API设置反向代理。以下是具有cors和反向代理设置的nginx配置:
server {
listen 80;
listen [::]:80;
server_name api.ZZZ.com;
set $cors '';
location / {
if ($http_origin ~ '^https?://(localhost|www\.ZZZ\.com|www\.ZZZ\.com|ZZZ\.com)') {
set $cors 'true';
}
if ($cors = 'true') {
add_header 'Access-Control-Allow-Origin' "$http_origin" always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,Width,X-Requested-With' always;
# required to be able to read Authorization header in frontend
add_header 'Access-Control-Expose-Headers' 'Authorization' always;
}
if ($request_method = 'OPTIONS') {
# Tell client that this pre-flight info is valid for 20 days
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
proxy_pass http://localhost:5000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
我的startup.cs
中也有以下内容:
services.AddCors(options =>
{
options.AddPolicy(corsName, builder =>
{
builder.WithOrigins("http://www.ZZZ.com", "http://ZZZ.com")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
及更高版本:
app.userCors(corsName);
但是我仍然收到以下CORS错误:
Access to XMLHttpRequest at 'http://api.ZZZ.com/YYY' from origin 'http://www.ZZZ.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
请帮助!
答案 0 :(得分:0)
您可以尝试使用SetIsOriginAllowedToAllowWildcardSubdomains
配置并添加通配符子域吗?这样。
使用ConfigureServices
方法。
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder
.SetIsOriginAllowedToAllowWildcardSubdomains()
.WithOrigins("https://*.example.com","https://example.com")
.AllowAnyMethod()
.AllowCredentials()
.AllowAnyHeader()
.Build()
);
});
在Configure
方法中
app.UseCors("CorsPolicy");