解决跨域问题

  • 环境: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();
    });
});
Logo

前往低代码交流专区

更多推荐