Asp.net Core 设置跨域

 No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://xxx' is therefore not allowed access

ASP.net Core 跨域有两种,全局和区域

全局跨域:

Startup.cs文件ConfigureServices方法中添加:

1.允许所有来源:

      services.AddCors(options =>
            options.AddPolicy("跨域策略名称",
            p => p.AllowAnyOrigin())
          );    

2.允许一个或多个具体来源:

        services.AddCors(options =>
        {
            options.AddPolicy("跨域策略名称", p =>
            {
                //多个IP用","隔开
                p.WithOrigins("http://localhost:xxx");
                p.AllowAnyHeader()
                p.AllowAnyMethod()
                p.AllowCredentials();
            });
        });

Configure方法中添加以下代码

app.UseCors("跨域策略名称");

 局部跨域,实现指定Controller或acttion跨域:

1.删去Configure中app.UseCors()

2.在Controller或Action上加特性[EnableCors("跨域策略名称")]

禁止跨域:

在Controller或者Action加上[DisableCors]特性

 

posted @ 2022-02-12 11:26  二姐1511  阅读(644)  评论(0编辑  收藏  举报