Asp.net core 跨域设置

时间:2023-03-09 16:22:35
Asp.net core 跨域设置

验证环境:

dotnet core 2.1/Asp.net core2.1

一、作用域在中间件层 

配置的方式是在startup.cs文件Configure(IApplicationBuilder app, IHostingEnvironment env)方法中增加跨域配置。官方示例:

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} app.UseCors(builder => builder.WithOrigins("http://example.com")); app.UseMvc();
}

使用app.UseCors(builder =>builder.WithOrigins("http://example.com"));
"http://example.com"为要允许跨域的地址,WithOrigins可以支持多个地址。

官方说明app.UseCors方法设置须在app.UserMvc 或者app.Run 前。

二、跨域策略定义

可在startup.cs文件ConfigureServices(IServiceCollection services)方法中定义策略,支持定义多个策略。官方示例:

 using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; namespace CorsExample4
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
// BEGIN01
options.AddPolicy("AllowSpecificOrigins",
builder =>
{
builder.WithOrigins("http://example.com", "http://www.contoso.com");
});
// END01 // BEGIN02
options.AddPolicy("AllowAllOrigins",
builder =>
{
builder.AllowAnyOrigin();
});
// END02 // BEGIN03
options.AddPolicy("AllowSpecificMethods",
builder =>
{
builder.WithOrigins("http://example.com")
.WithMethods("GET", "POST", "HEAD");
});
// END03 // BEGIN04
options.AddPolicy("AllowAllMethods",
builder =>
{
builder.WithOrigins("http://example.com")
.AllowAnyMethod();
});
// END04 // BEGIN05
options.AddPolicy("AllowHeaders",
builder =>
{
builder.WithOrigins("http://example.com")
.WithHeaders("accept", "content-type", "origin", "x-custom-header");
});
// END05 // BEGIN06
options.AddPolicy("AllowAllHeaders",
builder =>
{
builder.WithOrigins("http://example.com")
.AllowAnyHeader();
});
// END06 // BEGIN07
options.AddPolicy("ExposeResponseHeaders",
builder =>
{
builder.WithOrigins("http://example.com")
.WithExposedHeaders("x-custom-header");
});
// END07 // BEGIN08
options.AddPolicy("AllowCredentials",
builder =>
{
builder.WithOrigins("http://example.com")
.AllowCredentials();
});
// END08 // BEGIN09
options.AddPolicy("SetPreflightExpiration",
builder =>
{
builder.WithOrigins("http://example.com")
.SetPreflightMaxAge(TimeSpan.FromSeconds());
});
// END09
});
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(); if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} app.UseCors("AllowSpecificOrigins");
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
}
}

使用app.UseCors("AllowSpecificOrigins");调用具体的跨域策略,“AllowSpecificOrigins”为策略名,跨域作用域在中间层上。
策略定义和使用方法详见官方的参考文章(本文最后给出地址)。

三、作用域在MVC层

在使用MVC时,官方给出的3种设置方式,分别是Action前设置、Controller前设置、全局性设置。

  • Action

在Action 方法前增加标记EnableCors(策略名称).官方示例

 [HttpGet]
[EnableCors("AllowHeaders")]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}

EnableCors 在Microsoft.AspNetCore.Cors命名空间下。"AllowHeaders"为策略名称。

  • Controller

在Controller前增加标记EnableCors(策略名称).官方示例

[EnableCors("AllowSpecificOrigin")]
public class ValuesController : Controller
  • MVC全局(Globally)

官方说明是通过“CorsAuthorizationFilterFactory”过滤器方式给所有Controller增加跨域设置。官方示例:

 using Microsoft.AspNetCore.Mvc.Cors.Internal;

 ...

 public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
//...策略设置...
}); services.AddMvc();
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAllMethods"));
});
}

CorsAuthorizationFilterFactory在命名空间Microsoft.AspNetCore.Mvc.Cors.Internal下。“AllowAllMethods”为策略名称。

  • 禁用跨域

官方说明可以使用标记“DisableCors”设置Action或Controller跨域设置不起作用。官方示例:

 [HttpGet("{id}")]
[DisableCors]
public string Get(int id)
{
return "value";
}

DisableCors在命名空间Microsoft.AspNetCore.Cors下。

四、整体作用范围

作用范围,Middleware>Globally>Controller>Action。

生效优先顺序是Action,Controller,Globally,Middleware。即Action定义了跨域优先Controller生效,Controller优先Globally,Globally优先Middleware。

如果定义了跨域不生效,就要检查Action 和Controller 及Controller基类是否定义了其他的跨域设置。

官方参考文章:https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.1