angularcorsasp.net-core-webapiasp.net-core-8

CORS error accessing ASP.NET Core 8 Web API from Angular front-end


I've read every solution and I've tried them all so far, and nothing works.

I have an ASP.NET Core 8 Web API backend and a hybrid .NET 8/Angular 15 front-end. The front-end application can make GET requests to the API, but POST is blocked by CORS.

I've tried the following in the API:

builder.Services.AddCors(options =>
        {
            options.AddDefaultPolicy(builder => {
                builder.WithOrigins("http://localhost:1859");
                builder.WithMethods("GET", "POST");
                builder.AllowAnyHeader();
            });
        });

and

app.UseHttpsRedirection();
app.UseCors();
app.UseAuthorization();

along with

builder.Services.AddCors(options =>
        {
            options.AddDefaultPolicy(builder => {
                builder.AllowAnyOrigin();
                builder.AllowAnyMethod();
                builder.AllowAnyHeader();
            });
        });

The controller method (I've tried with and without [EnableCors()]):

[HttpPost] 
public async Task<int> Save(SaveContractRequest req)

Angular service method:

saveContract(req: SaveContractRequest) {
    return this.http.post<number>(this.settingsSvc.apiEndpoint + ReimbursementEndPoints.CONTRACTS_SAVE, req);
}

And yet I always get this error on POST:

Access to XMLHttpRequest at 'http://localhost/evms.api/api/Reimbursement/Contracts/Save' from origin 'http://localhost:1859' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I'm at a loss. I can't get any more permissive than "allow any origin, any header, and any method". Why doesn't this work? Why can't I call a controller with a POST method?


Solution

  • You should be using app.UseStaticFiles(); app.UseRouting() before enabling Cross-origin resource sharing (CORS) so that your route is recognized

    middleware pipeline

    The order of execution will be

    var app = builder.Build();
    
    app.UseHttpsRedirection();
    
    app.UseStaticFiles(); // 🔴 here it is
    app.UseRouting(); // 🔴 here it is
    
    app.UseCors();
    app.UseAuthorization();
    

    Link: UseCors and UseStaticFiles order