Asp.net core 跨域設置

驗證環境:web

dotnet core 2.1/Asp.net core2.1跨域

 

1、做用域在中間件層 app

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

 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能夠支持多個地址。async

官方說明app.UseCors方法設置須在app.UserMvc 或者app.Run 前。ui

 

2、跨域策略定義this

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

 

  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」爲策略名,跨域做用域在中間層上。
策略定義和使用方法詳見官方的參考文章(本文最後給出地址)。.net


3、做用域在MVC層code

在使用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<MvcOptions>(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下。

 

4、總體做用範圍

做用範圍,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

相關文章
相關標籤/搜索