首页 > 解决方案 > CORS 不适用于 .NET Core API 和 Angular 前端

问题描述

我已经阅读了类似的问题,尝试了其中提到的几个解决方案,但没有任何成功 - 问题很简单,我真的不知道到底有什么错误......

我有一个非常简单的 .NET Core API,我想在其上设置 CORS。

我试过这种方式(端点路由):https ://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-5.0#enable-cors-with-endpoint-routing

Startup.cs 中的 ConfigureServices() 和 Configure() 方法

完全是默认生成的,只是添加了 MSDN 的 CORS 相关代码。

      public void ConfigureServices(IServiceCollection services)
      {
           services.AddCors(options =>
           {
               options.AddPolicy(name: "Policy1",
                    builder =>
                    {
                        // I read the site url from appsettings.json but for now I want to keep the example as simple as I can
                        // var lpSolverFrontendUrl = Configuration.GetValue<string>("Cors:AllowedSite");
                        builder.WithOrigins("http://localhost:4200").AllowAnyHeader().AllowAnyMethod();
                    });
            });
            services.AddControllers();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseCors();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers().RequireCors("Policy1");
            });
        }

我的控制器类

    [Route("[controller]/[action]")]
    public class SimplexSolverController : Controller
    {
        public IActionResult Ping()
        {
            return Json(new { status = "OK" });
        }

        [HttpPost]
        public IActionResult Solve([FromBody] LPModelDto lpModelDto)
        {
            bool wrongFormat = false;
            string message = null;
            SimplexSolutionDto solution = null;
            //...
        }
        //...
   }

我已经尝试过的另一种方式(带有属性):https ://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-5.0#enable-cors-with-attributes

Startup.cs 这样

        public void ConfigureServices(IServiceCollection services)
        {
           services.AddCors(options =>
           {
               options.AddPolicy(name: "Policy1",
                    builder =>
                    {
                        // I read the site url from appsettings.json but I want to keep the example as simple as I can
                        // var lpSolverFrontendUrl = Configuration.GetValue<string>("Cors:AllowedSite");
                        builder.WithOrigins("http://localhost:4200").AllowAnyHeader().AllowAnyMethod();
                    });
            });
            services.AddControllers();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseCors();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

我的控制器类这样

我将EnableCors属性放在控制器方法上以启用 CORS。

    [Route("[controller]/[action]")]
    public class SimplexSolverController : Controller
    {
        public IActionResult Ping()
        {
            return Json(new { status = "OK" });
        }

        [EnableCors("Policy1")]
        [HttpPost]
        public IActionResult Solve([FromBody] LPModelDto lpModelDto)
        {
            bool wrongFormat = false;
            string message = null;
            SimplexSolutionDto solution = null;
             //...
        }
        //...
   }

无论我选择哪种方式,我都会在 DevTools 控制台中收到错误,例如:CORS 策略已阻止从源“http://localhost:4200”访问“http://localhost:4000/simplexsolver/solve”处的 XMLHttpRequest :请求的资源上不存在“Access-Control-Allow-Origin”标头。

我完全按照文章所说的但没有任何结果......我感谢任何帮助!

更新

我终于成功启用了CORS。可悲的是,我无法在 ConfigureServices 中设置任何类型的策略,因为如果我这样做,Access-Control-Allow-Origin 标头将在预检中具有“*”值(不是前端的地址)请求的响应。我使用的方式是:

现在我在 Startup.cs 中的两个方法如下所示:

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();
            services.AddControllers();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCors(options => options.WithOrigins(Configuration.GetValue<string>("Cors:AllowedSite")).AllowAnyMethod().AllowAnyHeader().AllowCredentials());

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

谢谢你给我的所有答案!我希望这对将来的某人有所帮助。但对我来说,将 CORS 与策略一起使用有什么问题仍然让我感到奇怪。

标签: c#asp.net-corecors

解决方案


用这个:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy("AllowOrigin", builder => 
                        builder.AllowAnyOrigin()
                               .AllowAnyHeader()
                               .AllowAnyMethod());
            });
         
            //...
        }

如果它不起作用,请将 Mvc 兼容版本设置为 3.0 使用

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

像这样:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy("AllowOrigin", builder => 
                        builder.AllowAnyOrigin()
                               .AllowAnyHeader()
                               .AllowAnyMethod());
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
            
            //...
        }

推荐阅读