把旧系统迁移到.Net Core 2.0 日记 (16) --Cors跨域访问

时间:2021-08-12 03:48:24

IE浏览器的Intranet局域网设置默认是可以跨域访问的.chrome就不可以.

这里说的跨域是指javascript代码不能跨域, 当然你在后端controller代码里用HttpClient.GetAsync(url) 这样去请求数据是不存在跨域问题的.

1. 在Startup.cs的ConfigureServices方法

public void ConfigureServices(IServiceCollection services)
{
  string[] origins = Configuration.GetValue<string>("CorsOrigin").Split(","); //从appsettings.json读取
  services.AddCors(c =>
    c.AddPolicy("AllowSpecificOrigin", policy =>
  {
    policy.WithOrigins(origins)
    .WithMethods("GET", "POST", "PUT", "DELETE");   })); }

2. 在startup.cs的Configure方法里

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors("AllowSpecificOrigin");
}

3. appsetting.json里增加一个

"CorsOrigin": "http://www.example1.com,http://www.example2.com",