Asp.net core 跨域设置

验证环境:

dotnet core 2.1/Asp.net core2.1

 

一、作用域在中间件层 

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

 1    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
 2         public void Configure(IApplicationBuilder app, IHostingEnvironment env)
 3         {
 4             if (env.IsDevelopment())
 5             {
 6                 app.UseDeveloperExceptionPage();
 7             }
 8 
 9          
10             app.UseCors(builder => builder.WithOrigins("http://example.com"));
11             
12             app.UseMvc();
13         }

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

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

 

二、跨域策略定义

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

 

  1 using System;
  2 using Microsoft.AspNetCore.Builder;
  3 using Microsoft.AspNetCore.Hosting;
  4 using Microsoft.AspNetCore.Http;
  5 using Microsoft.Extensions.DependencyInjection;
  6 using Microsoft.Extensions.Logging;
  7 
  8 namespace CorsExample4
  9 {
 10     public class Startup
 11     {
 12         // This method gets called by the runtime. Use this method to add services to the container.
 13         // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
 14         public void ConfigureServices(IServiceCollection services)
 15         {
 16             services.AddCors(options =>
 17             {
 18                 // BEGIN01
 19                 options.AddPolicy("AllowSpecificOrigins",
 20                 builder =>
 21                 {
 22                     builder.WithOrigins("http://example.com", "http://www.contoso.com");
 23                 });
 24                 // END01
 25 
 26                 // BEGIN02
 27                 options.AddPolicy("AllowAllOrigins",
 28                     builder =>
 29                     {
 30                         builder.AllowAnyOrigin();
 31                     });
 32                 // END02
 33 
 34                 // BEGIN03
 35                 options.AddPolicy("AllowSpecificMethods",
 36                     builder =>
 37                     {
 38                         builder.WithOrigins("http://example.com")
 39                                .WithMethods("GET", "POST", "HEAD");
 40                     });
 41                 // END03
 42 
 43                 // BEGIN04
 44                 options.AddPolicy("AllowAllMethods",
 45                     builder =>
 46                     {
 47                         builder.WithOrigins("http://example.com")
 48                                .AllowAnyMethod();
 49                     });
 50                 // END04
 51 
 52                 // BEGIN05
 53                 options.AddPolicy("AllowHeaders",
 54                     builder =>
 55                     {
 56                         builder.WithOrigins("http://example.com")
 57                                .WithHeaders("accept", "content-type", "origin", "x-custom-header");
 58                     });
 59                 // END05
 60 
 61                 // BEGIN06
 62                 options.AddPolicy("AllowAllHeaders",
 63                     builder =>
 64                     {
 65                         builder.WithOrigins("http://example.com")
 66                                .AllowAnyHeader();
 67                     });
 68                 // END06
 69 
 70                 // BEGIN07
 71                 options.AddPolicy("ExposeResponseHeaders",
 72                     builder =>
 73                     {
 74                         builder.WithOrigins("http://example.com")
 75                                .WithExposedHeaders("x-custom-header");
 76                     });
 77                 // END07
 78 
 79                 // BEGIN08
 80                 options.AddPolicy("AllowCredentials",
 81                     builder =>
 82                     {
 83                         builder.WithOrigins("http://example.com")
 84                                .AllowCredentials();
 85                     });
 86                 // END08
 87 
 88                 // BEGIN09
 89                 options.AddPolicy("SetPreflightExpiration",
 90                     builder =>
 91                     {
 92                         builder.WithOrigins("http://example.com")
 93                                .SetPreflightMaxAge(TimeSpan.FromSeconds(2520));
 94                     });
 95                 // END09
 96             });
 97         }
 98 
 99         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
100         public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
101         {
102             loggerFactory.AddConsole();
103 
104             if (env.IsDevelopment())
105             {
106                 app.UseDeveloperExceptionPage();
107             }
108 
109             app.UseCors("AllowSpecificOrigins");
110             app.Run(async (context) =>
111             {
112                 await context.Response.WriteAsync("Hello World!");
113             });
114         }
115     }
116 }

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


三、作用域在MVC层

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

  • Action

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

1 [HttpGet]
2 [EnableCors("AllowHeaders")]
3 public IEnumerable<string> Get()
4 {
5     return new string[] { "value1", "value2" };
6 }

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

 

  • Controller

 

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

 

[EnableCors("AllowSpecificOrigin")]
public class ValuesController : Controller

 

  • MVC全局(Globally)

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

 1 using Microsoft.AspNetCore.Mvc.Cors.Internal;
 2 
 3 ...
 4 
 5 public void ConfigureServices(IServiceCollection services)
 6 {
 7     services.AddCors(options =>
 8     {
 9      //...策略设置...
10      });
11 
12     services.AddMvc();
13     services.Configure(options =>
14     {
15         options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAllMethods"));
16     });
17 }

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

 

  • 禁用跨域

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

 

1 [HttpGet("{id}")]
2 [DisableCors]
3 public string Get(int id)
4 {
5     return "value";
6 }

       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

转载于:https://www.cnblogs.com/hobinly/p/9437143.html

你可能感兴趣的:(Asp.net core 跨域设置)