CORS 策略和 .NET Core 3.1 的问题 [英] Trouble with CORS Policy and .NET Core 3.1

查看:37
本文介绍了CORS 策略和 .NET Core 3.1 的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定我错过了什么,但似乎无法让我的 CORS 策略与 .NET Core 3.1 和 Angular 8 客户端一起使用.

Startup.cs:

 public void ConfigureServices(IServiceCollection services){//...//添加 CORS 策略services.AddCors(options =>{options.AddPolicy("foo",建造者 =>{//不是永久解决方案,只是尝试隔离问题builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();});});services.AddControllers();}公共无效配置(IApplicationBuilder 应用程序,IWebHostEnvironment 环境){如果 (env.IsDevelopment()){app.UseDeveloperExceptionPage();}app.UseHttpsRedirection();//使用 CORS 策略app.UseCors("foo");app.UseRouting();app.UseAuthorization();app.UseEndpoints(endpoints =>{端点.MapControllers();});}

错误消息客户端:

从源 'http://localhost:4200' 访问 XMLHttpRequest at 'https://localhost:8082/api/auth/' 已被 CORS 策略阻止:No 'Access-Control-Allow-请求的资源上存在 Origin' 标头.

更新:

尽管我 错误地配置了 CORS(并且下面接受的答案实际上对此有所帮助),但问题的根源是无关的.对于其他上下文,当使用 CLI 运行 API 和 Angular 应用程序时,该应用程序运行完全正常 - 我只是在将它们部署到 Web 服务器后才遇到此问题.

实际" 问题最终与 SQL 连接有关,我只是在向 API 添加平面文件错误日志记录并运行 SQL Server 跟踪以发现该应用程序是根本无法连接到 SQL.

我通常希望这只会返回 500,而我会在 10 秒内意识到这个问题——但是 CORS 配置错误意味着 500 实际上从未被返回,因为 CORS 中间件首先失败.至少可以说这非常令人沮丧!.然而,我想在这里补充一点,以防其他人发现自己处于这种情况,因为我追错了兔子",如果你愿意的话.修复 CORS 配置后,我意识到实际问题与 CORS 完全无关.

TL;DR;- 如果 CORS 策略设置不正确,有时非 CORS".NET 服务器端错误会作为 CORS 错误返回

参考文献:

https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#cors-with-named-policy-and-middleware

https://medium.com/swlh/cors-headers-with-dot-net-core-3-5c9dfc664785

解决方案

app.UseRouting();然后app.UseCors("foo");>

更改您的 Configure 方法,如下所示:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env){如果 (env.IsDevelopment()){app.UseDeveloperExceptionPage();}app.UseHttpsRedirection();app.UseRouting();//第一的//使用 CORS 策略app.UseCors("foo");//第二app.UseAuthorization();app.UseEndpoints(endpoints =>{端点.MapControllers();});}

它对我有用!

I'm not sure what I'm missing, but can't seem to get my CORS Policy working with .NET Core 3.1 and Angular 8 client-side.

Startup.cs:

        public void ConfigureServices(IServiceCollection services)
        {
            // ...

            // Add CORS policy
            services.AddCors(options =>
            {
                options.AddPolicy("foo",
                builder =>
                {
                    // Not a permanent solution, but just trying to isolate the problem
                    builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
                });
            });

            services.AddControllers();
        }

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

            app.UseHttpsRedirection();

            // Use the CORS policy
            app.UseCors("foo");

            app.UseRouting();

            app.UseAuthorization();

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

Error Message Client-side:

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

UPDATE:

Although I was configuring CORS incorrectly (and the accepted answer below did in fact help with that) the root of issue was unrelated. For additional context, the app was working completely fine when running the API and Angular app using the CLI - I was only having this issue after deploying them both to a web server.

The "actual" issue ended up being related to the SQL connection, which I only discovered after adding flat-file error logging to the API and running a SQL Server trace to find that the app wasn't able to connect to SQL at all.

I would normally expect this to just return a 500 and I would have realized the issue in a matter of 10 seconds - however the CORS mis-configuration meant a 500 was never actually being returned because the CORS middleware failed first. This was immensely frustrating to say the absolute least! . However I want to add that here in case others find themselves in this situation, as I was "chasing the wrong rabbit," if you will. After fixing the CORS configuration, I realized the actual issue was entirely unrelated to CORS.

TL;DR; - Sometimes "Non-CORS" .NET Server-side Errors Can Be Returned as CORS Errors If CORS policies Aren't Set Correctly

References:

https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#cors-with-named-policy-and-middleware

https://medium.com/swlh/cors-headers-with-dot-net-core-3-5c9dfc664785

解决方案

first app.UseRouting(); then app.UseCors("foo");

Change your Configure method like the following :

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

    app.UseHttpsRedirection();



    app.UseRouting();  // first
    // Use the CORS policy
    app.UseCors("foo"); // second

    app.UseAuthorization();

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

It worked for me !

这篇关于CORS 策略和 .NET Core 3.1 的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆