Access to XMLHttpRequest has been blocked by CORS policy ...

Shahin Alam 5 Reputation points
2023-03-06T03:02:33.78+00:00

I’m calling a backend ASP.NET Core C# API from Angular. I’m able to hit the controller, however, when it tries to access an external site, it’s getting this error:

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

net::ERR_BLOCKED_BY_CLIENT

This is currently happening in my development environment (localhost). Any feedback is greatly appreciated.

// My code here

var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

builder.Services.AddCors(options =>
{
    options.AddPolicy(name:MyAllowSpecificOrigins, 
        builder =>
    {
        builder.WithOrigins("http://localhost",
            "http://localhost:4200",
            "https://localhost:7230",
            "http://localhost:90")
        .AllowAnyMethod()
        .AllowAnyHeader()
        .SetIsOriginAllowedToAllowWildcardSubdomains();
    });
});

app.UseRouting();
app.UseHttpsRedirection();
app.UseCors(MyAllowSpecificOrigins);
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,118 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,165 questions
0 comments No comments
{count} vote

1 answer

Sort by: Most helpful
  1. JasonPan - MSFT 4,201 Reputation points Microsoft Vendor
    2023-03-06T05:39:18.75+00:00

    Hi @Shahin Alam,

    By analyzing the existing code, this problem is related to the order of middleware.

    The correct order should be:

    var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
    
    builder.Services.AddCors(options =>
    {
        options.AddPolicy(name:MyAllowSpecificOrigins, 
            builder =>
        {
            builder.WithOrigins("http://localhost",
                "http://localhost:4200",
                "https://localhost:7230",
                "http://localhost:90")
            .AllowAnyMethod()
            .AllowAnyHeader()
            .SetIsOriginAllowedToAllowWildcardSubdomains();
        });
    });
    
    
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();
    
    app.UseCors(MyAllowSpecificOrigins);
    
    app.UseAuthorization();
    ...
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Jason Pan