什么是跨域?
浏览器从一个域名的网页去请求另一个域名的资源时,域名、端口、协议任一不同,都是跨域
跨域的几种情况
1、端口和协议的不同
2、localhost和127.0.0.1虽然都指向本机,但也属于跨域
一般情况WebApi都是跨域请求,没有设置跨域一般会报以下错误
关键字 Access-Control-Allow-Origin cors
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:48057' is therefore not allowed access.
ASP.net Core 跨域有两种,全局和区域
1.设置特定来源可以跨域,打开Startup.cs文件 注入IConfiguration 修改ConfigureServices方法
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
在ConfigureServices方法中添加
services.AddCors(options =>
{
// Policy 名稱 CorsPolicy 是自訂的,可以自己改
options.AddPolicy("qwer", policy =>
{
// 設定允許跨域的來源,有多個的話可以用 `,` 隔開
string CorsUrl= Configuration.GetConnectionString("CorsOrigins");//通过注入的IConfiguration 获取appsetting.json中的自定义路径
string[] CoreArray = CorsUrl.Split(',');//appsetting.json中的配置
//policy.WithOrigins("http://localhost:8080", "http://192.168.0.86:8080","http://123.123.123.123:5555")//写死的方式 不方便
policy.WithOrigins(CoreArray)
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
appsetting.json文件
修改Configure方法
添加
app.UseCors("qwer");//必须位于UserMvc之前
2.允许所有来源 不建议使用
修改ConfigureServices方法
//配置跨域处理,允许所有来源:
services.AddCors(options =>
options.AddPolicy("自定义的跨域策略名称",
p => p.AllowAnyOrigin())
);
修改Configure方法
添加
app.UseCors("qwer");//必须位于UserMvc之前