繁体   English   中英

Web 应用程序 Cors .NET CORE 3.1 与 2.1

[英]Web Application Cors .NET CORE 3.1 vs 2.1

最近,我所做的一切都在慢慢切换到 .NET CORE 3.1,但是当我尝试移植一些 Web 应用程序(Restful API)时,我遇到了 Cors 问题。

来自运行 .NET CORE 2.1 的项目的代码:

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

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseCors("AllowAnyOrigin");

            app.UseHttpsRedirection();

            app.UseMvc();
        }

来自运行 .NET CORE 3.1 的项目的代码:

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

            services.AddCors(options =>
            {
                options.AddPolicy("AllowAnyOrigin",
                builder => builder
                    .AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader());
            });

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

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseCors("AllowAnyOrigin");

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

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

当我向运行 2.1 的 API 发出请求时,一切都按预期进行,但是如果我尝试向运行 3.1 的 API 发出相同的请求,则会收到 405 错误(方法不允许错误)。

有没有其他人遇到过这个问题,如果有,解决方法是什么?

在您的配置方法中,移动:

app.UseCors("AllowAnyOrigin");

在两者之间

app.UseRouting();

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

文档中有一条警告,指出必须在这两种方法之间配置 cors 中间件,否则中间件将停止运行。

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

请参阅标有“将 CORS 策略应用于所有端点”的部分

配置管道中的组件非常棒,因为它可以让您进行控制,但由于排序限制而带来巨大的痛苦,我个人正在等待有人创建一个 VS 附加组件来分析这些组件并发出警告。 如果有人如此倾向,那将是一个伟大的项目。

暂无
暂无

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

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