asp.net-web-api – 如何在ASP.NET 5和MVC 6中启用跨源请求(CORS)?

我想在使用MVC 6构建的API启用CORS,但所有当前文档引用该框架的早期版本。

解决方法

关于新的Cors功能的注释很轻,但是我能够通过查看新的类和方法在我的解决方案中工作。我的Web API startup.cs看起来像这样。你可以看到如何使用新的CorsPolicy类来构造你的起源和策略。并使用AddCors和UseCors方法启用CORS。
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();
 }

您还可以在控制器中引用具有新属性的策略,如此

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

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....