這裏列舉幾個通過驗證的可用的CORS使用示例,api
方便在須要的時候能夠直接使用跨域
示例1app
#region snippet2 public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy(MyAllowSpecificOrigins, builder => { //1.可用 //builder.WithOrigins("http://example.com", // "http://www.contoso.com", // "http://localhost:65317"); builder.AllowAnyOrigin(); //2.可用 }); }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); } #endregion #region snippet3 public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseCors(MyAllowSpecificOrigins); app.UseHttpsRedirection(); app.UseMvc(); } #endregion
這種比較常見,即在ConfigureServices中添加中間件及定義其策略;而在Configure中把中間件設置到管道中ui
示例2spa
public void ConfigureServices(IServiceCollection services) { //services.AddCors(); //經試驗,此句加或者不加,都是能夠的 services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); } #region snippet2 public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } // Shows UseCors with CorsPolicyBuilder. app.UseCors(builder => { builder.WithOrigins("http://example.com", "http://www.contoso.com", "https://localhost:44375", "http://localhost:65317"); }); app.UseHttpsRedirection(); app.UseMvc(); } #endregion
注意,這個示例中,直接在Configure中的app.UseCors中設置的跨域的一些要求,這種寫法經試驗也是能夠的code
示例3中間件
public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddDefaultPolicy( builder => { builder.WithOrigins("http://example.com", "http://www.contoso.com", "http://localhost:65317"); }); options.AddPolicy("AnotherPolicy", builder => { builder.WithOrigins("http://www.contoso.com", "http://localhost:65317") .AllowAnyHeader() .AllowAnyMethod(); }); }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseHttpsRedirection(); app.UseMvc(); }
經試驗發現,像這種沒有在Configure中使用app.UseCors的,應該都屬於局部設置跨域的,須要在相應的Controller或者Action方法上,使用註解:blog
//[EnableCors("AnotherPolicy")] //這種事有名稱的策略的註解添加 [EnableCors()] //這種是模式策略的註解添加 [Route("api/[controller]")] [ApiController] public class ValuesController : ControllerBase
注意,即便是默認的策略也是須要使用註解進行聲明的,不然會跨域錯誤。默認的策略只是說不用在註解中聲明策略名而已ip