如何在ASP.NET Core MVC中启用跨域请求(CORS)

问题描述:

我想在使用ASP.NET Core MVC构建的API上启用CORS,但是所有当前文档都引用了该框架的早期版本.

I'd like to enable CORS on an API built with ASP.NET Core MVC, but all the current documents refer to earlier versions of that framework.

Cors新增功能的注释很浅,但是我可以通过查看新的类和方法使其在我的解决方案中起作用.我的Web API startup.cs 看起来像这样.您可以看到如何通过使用新的CorsPolicy类来构造您的血统和政策.并使用AddCorsUseCors方法启用CORS.

The notes on the new Cors features are very light, but I was able to get it working in my solution by looking at the new classes and methods. My Web API startup.cs looks like this. You can see how you can construct your origins and policies her by using the new CorsPolicy class. And enabling CORS with the AddCors and UseCors methods.

 public void ConfigureServices(IServiceCollection services)
 {
     services.AddMvc();
     //Add Cors support to the service
     services.AddCors();

     var policy = new Microsoft.AspNet.Cors.Core.CorsPolicy();

     policy.Headers.Add("*");    
     policy.Methods.Add("*");          
     policy.Origins.Add("*");
     policy.SupportsCredentials = true;

     services.ConfigureCors(x=>x.AddPolicy("mypolicy", policy));

 }


 public void Configure(IApplicationBuilder app, IHostingEnvironment  env)
 {
     // Configure the HTTP request pipeline.

     app.UseStaticFiles();
     //Use the new policy globally
     app.UseCors("mypolicy");
     // Add MVC to the request pipeline.
     app.UseMvc();
 }

您也可以像这样使用新属性在控制器中引用策略

You can also reference the policy in the controllers with the new attributes like so

[EnableCors("mypolicy")]
[Route("api/[controller]")]