Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 887
Warren Ayen-Tolson Avatar asked Sep 03 '25 16:09

Warren Ayen-Tolson


2 Answers

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

like image 193
naveen Avatar answered Sep 05 '25 06:09

naveen


In Angular you can setup the proxy create a proxy.conf.json folder inside src folder in angular app and add the below code (modify the port number and api name)

"/yourapi": {
   "target": "http://localhost:PORT/",
   "secure": false,
   "changeOrigin": true
 }
}

Proxy documentation for angular

like image 26
boolean_values Avatar answered Sep 05 '25 04:09

boolean_values