解決跨域問題
環境:NET 6
項目:WebAPI+Vue
問題還原
Access to XMLHttpRequest at '(請求路徑)' from origin
'http://localhost:8080' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
跨域(CORS)請求:同源策略/SOP(Same origin
policy)是一種約定,由Netscape公司1995年引入瀏覽器,它是瀏覽器最核心也最基本的安全功能,如果缺少了同源策略,瀏覽器很容易受到XSS、CSFR等攻擊。所謂同源是指"協議+域名+端口"三者相同,即便兩個不同的域名指向同一個ip地址,也非同源。
瀏覽器和服務器實現跨域(CORS)判定的原理
解決方式
添加受信賴的域
var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
app.UseCors(MyAllowSpecificOrigins);//啟用跨域問題
//Program.cs
builder.Services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
//添加收信賴的地址
builder.WithOrigins("http://localhost/8080", "http://localhost/8081")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
或者在配置文件中配置
//Program.cs
builder.Services.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins, builder =>
{
builder
.WithOrigins(
configuration["App:CorsOrigins"]
.Split(",", StringSplitOptions.RemoveEmptyEntries)
.ToArray()
)
.SetIsOriginAllowedToAllowWildcardSubdomains()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
//appsetting.json
"App": {
"CorsOrigins": "http://localhost/8080"
}
允許所有域
builder.Services.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins, builder =>
{
builder.AllowAnyMethod()
.SetIsOriginAllowed(_ => true)
.AllowAnyHeader()
.AllowCredentials();
});
});
