简体   繁体   English

C#Net Core:在API中启用Cors后,它仍然指出被CORS策略阻止

[英]C# Net Core: After enabling Cors in API, it still states blocked by CORS policy

I created a backend Net Core API which works in VS and Postman. 我创建了一个可以在VS和Postman中使用的后端Net Core API。 However, when creating an Angular CLI front end, I receive this error. 但是,在创建Angular CLI前端时,出现此错误。 It does not make sense, since I enabled Add Cors for AllowAnyOrigin Below. 这没有任何意义,因为我在下面启用了为AllowAnyOrigin添加Cors。

Angular error: 角度误差:

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 https://docs.microsoft.com/zh-cn/aspnet/core/security/cors?view=aspnetcore-2.2

You need to add the CORS middleware to the pipeline as well: 您还需要将CORS中间件添加到管道中:

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

When you call AddCors(), you are adding the services needed by the CORS middleware, as well as defining a policy. 调用AddCors()时,您将添加CORS中间件所需的服务,并定义策略。 But you need to apply the policy in the middleware pipeline as well. 但是您也需要在中间件管道中应用该策略。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM