如何在 ASP.NET Core MVC 中启用跨域请求 (CORS) [英] How do you enable cross-origin requests (CORS) in ASP.NET Core MVC

查看:29
本文介绍了如何在 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]")]  

这篇关于如何在 ASP.NET Core MVC 中启用跨域请求 (CORS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆