Allowing CORS on Localhost
Imagine the scenario your developing an API in .NET 6 and a front end in React. Locally you'd like to run both your API and front end and have the front end call the API. That's when you discover the CORS issue.
What is CORS?
CORS stands for cross-origin resource sharing. It's one of the browser's protections against malicious activity that checks with a server if the domain a request is originating from should actually be able to call HTTP endpoints on the provider.
The server (that's your API) will return if a domain is permitted to make a request to a given endpoint or not. If it's not you'll see a CORS error in the browsers network tab.
When your API and front-end code are running on the same domain this isn't an issue because there's no cross-origin to deal with. However, locally your front-end and backend api are likely on different localhost ports.
How to update ASP.NET CORS settings
In your program.cs file where builder.Build() and app.Run() are being called we need to add some extra logic.
1// Program.cs2// A string to name the policy3string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";45var builder = WebApplication.CreateBuilder(args);67// Add the cors policy8builder.Services.AddCors(o => o.AddPolicy(9 MyAllowSpecificOrigins, builder =>10 {11 builder.WithOrigins("http://localhost:3000") //Update with correct port number of front-end12 .AllowAnyHeader()13 .AllowAnyMethod();14 }));1516// There likely a lot of code between this bit and the next line1718var app = builder.Build();19// Other code omited2021// Tell the APP to use CORS22app.UseCors(MyAllowSpecificOrigins);23app.Run();
To avoid this having any effect on production you can also wrap is in an environment check.
1if (app.Environment.IsDevelopment())2{3 app.UseCors(MyAllowSpecificOrigins);4}