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]")]

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...