简体   繁体   中英

CORS error after upgrade from .NET Core 3.1 to .NET 6

I recently upgraded a relatively large web API from .NET Core 3.1 to .NET 6 and am getting a no Access-Control-Allow-Origin header CORS error. I have not moved to the minimal hosting model, but I understand from the docs that this is not necessary and the old model should continue to work. I include code from startup and program below and what I had to change to make the upgraded project work. Note that everything else works properly.

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<ForwardedHeadersOptions>(options =>
        {
            options.ForwardedHeaders =
                ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
        });
    services.AddCors(options => options.AddPolicy("CorsPolicy",
            builder =>
            {
                builder.AllowAnyMethod()
                    .WithOrigins(Configuration.GetSection("AllowedOrigins").Get<string[]>())
                    .SetIsOriginAllowed(origin => true)
                    .AllowAnyHeader();
            }));
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory, IHostApplicationLifetime appLifetime)
{
    app.UseCors("CorsPolicy");
}

Note that * is returned from "AllowedOrigins".

Program.cs

private static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .UseSerilog()
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder
                    .UseKestrel()
                    .UseContentRoot(Directory.GetCurrentDirectory())
                    
                    .UseUrls(Configuration.GetValue<bool>("App:UsesHttps") 
                        ? $"{Configuration.GetValue<string>("App:HttpUrl")}, " +
                          $"{Configuration.GetValue<string>("App:HttpsUrl") }" 
                        : $"{Configuration.GetValue<string>("App:HttpUrl")}")
                    .UseStartup<Startup>();
            });

For the upgrade to .NET 6, nothing in Startup.cs has changed. In Program.cs , .UseUrls does not work anymore and instead I have it defined in appsettings and I have removed the call to .UseUrls .

Appsettings (.NET Core 3.1)

"App": {
        "UsesHttps": false,
        "HttpUrl": "http://0.0.0.0:5005",
        "HttpsUrl": "https://0.0.0.0:5001"
    },

Appsettings (.NET 6)

"Kestrel": {
        "Endpoints": {
            "Http": {
                "Url": "http://localhost:5005"
            }
        }
    },

Nothing else in the code has changed, and all I have done is update packages. I fail to see how they would influence a CORS error.

The app is running in a Docker container behind Nginx serving as a reverse proxy. I have not made any changed to the Nginx settings. The app is listening on HTTP only as Nginx handles the HTTPS connection. Again, this works when the app is built against .NET Core 3.1. I have read the documentation about upgrading to .NET 6 and I cannot find anything that would explain this kind of a change.

don't know if this will help you. We have the following in our API in the program.cs

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // Other code left out here

        app.UseAuthentication();

        // Allow CORS for any origin, method or header
        app.UseCors(policy =>
                policy.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());

        app.UseAuthorization();

     }

If I remember correctly the order of things is pretty important. I don't see Authentication and Authorization in your code. Don't know if you need that or not. There's a remark at this code as it might be allowing too much. We still have to investigate that.

Any updates on this? I face a same issue when migrated from .NET5 to .NET6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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