CORS 对 dotnet core 3.1 中预检的响应问题

Posted

技术标签:

【中文标题】CORS 对 dotnet core 3.1 中预检的响应问题【英文标题】:Problems with CORS Response to preflight in dotnet core 3.1 【发布时间】:2020-07-31 09:58:00 【问题描述】:

我正面临这个问题:

从源“http://localhost:4200”访问“http://localhost:5000/api/surpactemp/”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:预检请求不允许重定向。

在后端我尝试了这种方法但没有成功:

.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()

我一直在尝试使用 Microsoft 参考(如下)解决问题的几种方法,但到目前为止都没有成功。 另外,我已经尝试过不在 Angular 上传递 headers 对象,然后,我收到错误:

请求中没有“Access-Control-Allow-Origin”标头

环境

Dotnet Core 3.1 角度 8

后端:Startup.cs

//ConfigureServices
services.AddCors(options =>

    options.AddPolicy(name: "CorsPolicy",
        builder => builder.WithOrigins("http://localhost:4200")
                          .WithHeaders(HeaderNames.ContentType, "application/json")
                          .WithMethods("PUT", "DELETE", "GET", "OPTIONS", "POST")        
        );
);

//Configure
 app.UseHttpsRedirection();

 app.UseRouting();

 app.UseCors("CorsPolicy");

 app.UseAuthorization();

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

前端:form-service.ts

httpOptions = 
    headers: new HttpHeaders(
      // 'Content-Type': 'application/json',
      // 'withCredentials': 'false',
      // 'Access-Control-Allow-Origin': '*',
      'Content-Type': 'application/json'
    )
;

return this.httpClient.post('http://localhost:5000/api/surpactemp/', JSON.stringify(data.path), this.httpOptions);

参考:https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#preflight-requests

【问题讨论】:

UseCors 的电话在哪里?它在中间件管道设置中的位置很重要。 @KirkLarkin 在后端部分,app.UseCors("CorsPolicy") 是的,我知道。我的意思是它在Startup.Configure 内的什么位置?之间还有哪些电话?中间件顺序很重要,因此可能您的顺序有误。 【参考方案1】:

我发现了问题,app.UseHttpsRedirection() 方法需要https 客户端。

Startup.csConfigure 方法上:

//app.UseHttpsRedirection(); <-- Commented this line

app.UseRouting();

app.UseCors();

app.UseAuthorization();

【讨论】:

谢谢,节省了我一些时间,我也在查询一个 http 端点 谢谢。也帮助了我。【参考方案2】:
services.AddCors(); // Make sure you call this previous to AddMvc
services.AddMvc();       

 app.UseCors(
     options => options.WithOrigins("http://localhost:4200","https://localhost:4200")
                .AllowAnyHeader().AllowAnyMethod().AllowCredentials()
             );

编辑:

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

            app.UseCors(
         options => options.WithOrigins("http://localhost:4200", "https://localhost:4200").AllowAnyHeader().AllowAnyMethod().AllowCredentials());




            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseAuthorization();


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

             

【讨论】:

同样,没用...从源 'localhost:5000/api/surpactemp' 访问 XMLHttpRequest 已被 CORS 策略阻止:否 'Access-Control-Allow-Origin'请求的资源上存在标头。【参考方案3】:

这个解决方案解决了我的问题:

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.AddControllers();
            services.AddCors();
        

        // 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();
            

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseCors(
                options => options.SetIsOriginAllowed(x => _ = true).AllowAnyMethod().AllowAnyHeader().AllowCredentials()
            );

            app.UseAuthorization();

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

来自https://github.com/dotnet/aspnetcore/issues/16672

【讨论】:

【参考方案4】:

看起来这就是问题所在(当我意识到重定向正在我的服务中使用app.UseHttpsRedirection(); 完成并且javascript调用是“http”而不是“https”时就消失了。我希望错误更具体,但这修复了它!

【讨论】:

【参考方案5】:

您可以使用代理配置。

看看这个https://www.youtube.com/watch?v=D9oFe6rHjpY

【讨论】:

嗨,我已经在 Angular 上使用代理尝试过这种方式,但效果不佳......

以上是关于CORS 对 dotnet core 3.1 中预检的响应问题的主要内容,如果未能解决你的问题,请参考以下文章

dotNet Core 3.1 使用 Aspose (部署 Docker)

如何将 ILoggerFactory 添加到启动 dotnet core 3.1

Dotnet Core 3.1:如何将 AddJsonFile 与文件的绝对路径一起使用?

抛出异常:'System.PlatformNotSupportedException'。如何在 dotnet core 3.1 中加密和解密安全字符串?

在 Visual Studio 16.6 中将仅内容包导入 DotNet Core 3.1 项目

如何将 c# dotnet core 3.1 微服务流绑定到涡轮服务器流