Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Failed to enable CORS in asp .net core 6.0 Web Api

I am working a asp .net core 6.0 web Api.(We are moving to asp .net core from 3.1 to 6.0)

I did enable cors in our asp .net core 6.0 project and works fine earlier (this morning ). But Now I faced cors error.

Error: Access to XMLHttpRequest at 'http://localhost:5000/api/user/authenticate' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

I revoked my git commits and checked. still It give CORS error

This is my program.cs

var app = builder.Build();

app.UseHttpsRedirection();
app.UseForwardedHeaders();
app.UseCors(builder => builder.WithOrigins("*")/*.AllowAnyOrigin()*/.AllowAnyHeader().AllowAnyMethod());
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

The same code worked fine earlier in asp .net core 6.0. Also Now In asp .netcore 3.1 project It is working fine.

Note: I searched about this error. And Tried same as on this answer How to enable cors in ASP.NET Core 6.0 Web API project?. But It did not work for me.

What is the mistake I did? Why this error occurs ( Today morning I did not face this error. But now facing this error. I revoked my new commits too. But CORS error)

Is there any other reasons to get this CORS error. I guess mistake is on my asp.net core 6.0 project, because asp .net core 3.1 project is working fine

like image 495
hanushi-thana Avatar asked Sep 13 '25 19:09

hanushi-thana


1 Answers

app.UseCors should come after app.UseRouting();

according to the official documentation https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-6.0

like image 79
Joe Avatar answered Sep 15 '25 10:09

Joe