I am migrating a .NET Core Web API from 2.2 to 3.1. I have followed the Microsoft migration instructions and placed the call to the CORS middleware between UseRouting and UseEnpoints. However, I am still getting CORS errors.
In the ConfigureServices method, I have:
services.AddCors();
In the Configure method, I have:
app.UseRouting();
app.UseCors(options => options
.AllowAnyOrigin()
.AllowAnyHeader().AllowAnyMethod()
);
app.UseAuthentication();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
The console error in the web browser is:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/users/login. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/users/login. (Reason: CORS request did not succeed).
Diagnostics:
I tried following Microsoft's documentation Enable Cross-Origin Requests (CORS) in ASP.NET Core, but it uses outdated references, such as; UseMvc and IHostingEnvironment.
I tried creating a brand new Web API and Ember Web-UI, but that did not work either. You can find a simple example getting-started-with-ember-js-and-net-core-3
Any idea what is causing the problem?
The ideal bounty reward will go to the answer that works. Preferably, a working bare-bones project will be posted on Git.
Note: I am allowing any origin right now just so I can get it to work. Ultimately, this will need to work with a Web-UI that is on http://localhost:4200
Update
The status code received is HTTP 405 - method not allowed. The method in question is an OPTIONS method.
The .NET Core 2.2 to 3.0 migration document is incorrect. The call to UseCors();
needs to be placed before the UseRouting()
function. I went ahead and added it before the UseHttpsRedirection()
as I saw that in an implementation on another site.
https://learn.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.1&tabs=visual-studio#migrate-startupconfigure
In ConfigureServices
services.AddCors(options =>
{
options.AddPolicy("CorsApiPolicy",
builder =>
{
builder.WithOrigins("http://localhost:4200")
.WithHeaders(new[] { "authorization", "content-type", "accept" })
.WithMethods(new[] { "GET", "POST", "PUT", "DELETE", "OPTIONS" })
;
});
});
In Configure
app.UseCors("CorsApiPolicy");
//app.UseHttpsRedirection();
app.UseJsonApi();
app.UseRouting();
app.UseAuthentication();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With