Search code examples
angularasp.net-mvcasp.net-corecors

CORS is not working for me, despite the fact that I have already added it


I want to execute a request from my Angular 17 application to an ASP.NET Core(.NET 8) server, but I get the error

Access to XMLHttpRequest at 'http://localhost:5000/api/user' from origin 'https://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Error

**I've already added CORS support. Here is the code for app.component.ts

import { HttpClient } from '@angular/common/http';

...

export class AppComponent implements OnInit{

...

  constructor(private http: HttpClient) { }

    ngOnInit(): void {
  this.http.get('http://localhost:5000/api/user', {
    headers: ({
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Expose-Headers': '*'
    })
  }).subscribe({
    next: response => this.users = response,
    error: error => console.log(error),
    complete: () => console.log('Request has completed')
  })
}

And here is the Program.cs code

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCors(options =>
{
    options.AddPolicy(name: "AngularOrigin", policy =>
    {
        policy.WithOrigins("http://localhost:4200").AllowAnyMethod().AllowAnyHeader().AllowCredentials();
    });
});

...

var app = builder.Build();

app.UseCors("AngularOrigin"); ///First middleware

I've probably gone through all the tips for solving this problem. I added CORS support to the controllers:

    [ApiController]
    [Route("api/[controller]")] //api/user
    public class UserController : ControllerBase
    {
        ...

        [EnableCors("AngularOrigin")]
        [HttpGet]
        public async Task<ActionResult<IEnumerable<AppUser>>> GetUsers()
        {
            ...
        }

        [EnableCors("AngularOrigin")]
        [HttpGet("{id}")]   //api/user/2
        public async Task<ActionResult<AppUser>> GetUser(int id)
        {
            ...
        }
    }
}

I have changed appsettings.Development.json

{
  "AllowedOrigins": "https://localhost:4200",
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },

   ...

}

I also deleted proxy.conf.js in an attempt to solve this problem, but to no avail.

P.S:I don't want to use a proxy server to get around this problem


Solution

  • You should double check your URIs: in the appsettings you use https, in the .Net code you don't(but then again in the example provided you don't use the app settings value).

    So check if your app is served on https/http, double check the port and make sure you build the .Net app with the configuration you changed(development, release, debug...).

    It should look like this:

    Config file:

    "AllowSpecificOrigin": [ "http://localhost:4200" ]
    

    .Net

         services.AddCors(options =>
            {
                options.AddPolicy("POLICY", builder =>
                {
                    builder
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                    var orig = this.Configuration.GetSection("AllowSpecificOrigin").Get<List<string>>();
                    if (orig!= null)
                    {
                        builder.WithOrigins(orig.ToArray());
                    }
                });
            });
            
            
    ___________________________
     app.UseCors("POLICY");
    

    Another important note, you might have misunderstood the "Access-Control-Allow-Origin" header. This is the response header added by the server, not by the client.