【问题标题】:C# Net Core: After enabling Cors in API, it still states blocked by CORS policyC# Net Core:在 API 中启用 Cors 后,仍处于 CORS 策略阻止状态
【发布时间】:2019-05-25 06:08:07
【问题描述】:

我创建了一个在 VS 和 Postman 中工作的后端 Net Core API。 但是,在创建 Angular CLI 前端时,我收到此错误。这没有任何意义,因为我为 AllowAnyOrigin 下面启用了添加 Cors。

角度错误:

Access to XMLHttpRequest at 'https://localhost:xxxx/api/values' from origin 'http://localhost:xxxx' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Startup.cs

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddCors((options =>
            { options.AddPolicy("AllowAllOrigins", builder => builder.AllowAnyOrigin());}));

        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseCors();
            // Shows UseCors with CorsPolicyBuilder.
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc();
        }
    }
}

https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.2

【问题讨论】:

标签: c# angular asp.net-core .net-core cors


【解决方案1】:

您还需要将 CORS 中间件添加到管道中:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseCors("AllowAllOrigins");
    // Other middleware
}

当您调用 AddCors() 时,您正在添加 CORS 中间件所需的服务,以及定义策略。 但是您还需要在中间件管道中应用该策略。

【讨论】:

    猜你喜欢
    • 2019-07-01
    • 1970-01-01
    • 2020-11-02
    • 1970-01-01
    • 2021-10-15
    • 2021-06-22
    • 2017-07-05
    • 1970-01-01
    • 2020-04-14
    相关资源
    最近更新 更多