Allowing CORS on Localhost

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.cs
2// A string to name the policy
3string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
4
5var builder = WebApplication.CreateBuilder(args);
6
7// Add the cors policy
8builder.Services.AddCors(o => o.AddPolicy(
9 MyAllowSpecificOrigins, builder =>
10 {
11 builder.WithOrigins("http://localhost:3000") //Update with correct port number of front-end
12 .AllowAnyHeader()
13 .AllowAnyMethod();
14 }));
15
16// There likely a lot of code between this bit and the next line
17
18var app = builder.Build();
19// Other code omited
20
21// Tell the APP to use CORS
22app.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}
Tagged: