廢話: 以前總是看別人博客,但是連評論都懶得給一個,於是心有愧疚,開始寫寫東西。本人不是科班出生的CODER,只是看多了,懂一些,瞭解一些思想,也不會動手CODING,也就把看到的換種話記錄下來。最近瞭解了一下asp.net core 的pipeline,認識了CORS,這篇文章就是把關於CORS的 ...
廢話:
以前總是看別人博客,但是連評論都懶得給一個,於是心有愧疚,開始寫寫東西。本人不是科班出生的CODER,只是看多了,懂一些,瞭解一些思想,也不會動手CODING,也就把看到的換種話記錄下來。最近瞭解了一下asp.net core 的pipeline,認識了CORS,這篇文章就是把關於CORS的Microsoft知識文檔用自己的話翻譯一下。
正文:
參考:
https://docs.microsoft.com/en-us/aspnet/core/security/cors
CORS(Cross Origin Resource Sharing),是一種跨域資源共用方式,由於瀏覽器“same-origin"(同源同策)的限制,其在實際應用中產生,同是W3C標準
至於何為SAME-ORIGIN:
- 協議相同,比如http、https、file等
- 域相同,比如www.baiud.com
- 埠相同
如何使用CORS
使用方法一:全局應用
.net core 的CORS模塊位於Microsoft.AspNetCore.Cors的nuget包
在asp.net core 中的services和middleware配置CORS
添加引用:
using Microsoft.AspNetCore.Cors
startup.cs
public void ConfigurationServices(IserviceCollection services) { services.AddCors() } public void Configure(IApplicationBuilder app,IHostingEnviroment env,ILoggerFactory loggerFactory) { app.UseCors(builder=> builder.WithOrigins("http://localhost:5000”); ); }
註意:
- AddCors()優先於其他任何服務
- builder.WithOrigins(url)的參數不能以‘/’結尾
- builder有一些chain method ,是用於過濾請求的,可自行查閱
使用方法二:命名使用
先定義一個或多個CORS策略,在controller、class、function等對象上根據策略名字,在attribute中使用
startup.cs
public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy("AllowAOrigin", builder => builder.WithOrigins("http://example.com")); options.AddPolicy("AllowBOrigin", builder => builder.WithOrigins("http://example.com")) }); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseCors("AllowAOrigin"); } //如果是MVC APP,只需要add service,不需要配置middleware
在attribute中使用CORS
[HttpGet] [EnableCors("AllowSpecificOrigin")] public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; }
限制所有controller
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.Configure<MvcOptions>(options => { options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAOrigin")); }); }
到這裡CORS基本用法差不多了,細節之處可見官網文檔,英語好的可以自行看英文文檔.至於這個東西在實際什麼項目中怎麼應用我也不清楚,不過我用在分離前後端上倒是好用。