Fix for Visual Studio 2022 Angular/Swagger Web API “No ‘Access-Control-Allow-Origin’ header is present on the requested resource” Error

I was building a simple Angular web API app based on the default WeatherForecast app that comes with Visual Studio 2022. Using Nuget Package Manager I added the "Swashbuckle.AspNetCore" package so that API JS services can be created using Swagger. Managed to get this all working correctly, but every time upon running the app I ran into this annoying error in the browser console, when trying to call a Swagger created service :

Access to XMLHttpRequest at 'https://localhost:7267/WeatherForecast/GetSomeData' from origin 'https://localhost:44488' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Normally with this kind of error in Linux you can just add an "Access-Control-Allow-Origin" header in nginx, but this was Visual Studio 2022 and it runs a npm server via Program.cs.

The solution was to install (using Nuget Package Manager) Microsoft.AspNetCore.Cors and then some code to add the CORS header for "localhost" in Program.cs :

var builder = WebApplication.CreateBuilder(args);

// add Cors policy - this has to be run before everything else
builder.Services.AddCors(options => options.AddPolicy("ApiCorsPolicy", builder =>
{
  builder.WithOrigins("https://localhost:44488").AllowAnyMethod().AllowAnyHeader().AllowCredentials();
}));

...
var app = builder.Build();
// now use the CORS policy (make sure is first too)
app.UseCors("ApiCorsPolicy"); // enable Cors

Done!

Thanks to https://stackoverflow.com/questions/44379560/how-to-enable-cors-in-asp-net-core-webapi for the info.

Leave a Reply