Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Core 3.1 CORS not working on Ember (3.12) web UI

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.

like image 710
J Weezy Avatar asked Dec 13 '22 09:12

J Weezy


1 Answers

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();
});
like image 136
J Weezy Avatar answered Dec 20 '22 16:12

J Weezy