繁体   English   中英

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

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

我创建了一个可以在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.

启动文件

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/zh-cn/aspnet/core/security/cors?view=aspnetcore-2.2

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

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

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

暂无
暂无

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

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