ASP.NET – How to add a CORS policy to enable requests from the browser

When you send requests from the browser, you’ll run into CORS errors unless you’ve explicitly added a CORS policy that allows your requests.

I’ll show an example of adding a simple CORS policy that allows all origins for all endpoints (thus allowing all requests from the browser). To add a CORS policy, you can add two lines to the initialization code:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddCors(o =>
	o.AddDefaultPolicy(b =>
		b.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()));

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseCors();

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();
Code language: C# (cs)

Note: If you’re not using the latest project style (top-level statements), add these calls to Startup.ConfigureServices() and Startup.Configure().

Put whatever CORS policy makes sense for you. In the code above, I am simply allowing everything.

Next, I’ll show how to test that the CORS policy works as expected.

Test CORS locally

To test this locally you can call your web API from a browser from a page running on a different port. Chrome enforces CORS even when the port number is different, so that makes things simple for us to test this.

I have the following setup:

  • My ASP.NET web API is running on localhost:44379
  • My test page is running on localhost:44395

1 – Create a web page that calls your endpoint

I have a page with a button that says [Send ping]. It uses the fetch API to send a request to my web API endpoint and logs the results.

<script type="text/javascript" language="javascript">

    function sendPing() {
        fetch("https://localhost:44379/ping")
            .then(data => console.log(data))
            .then(res => console.log(res))
        .catch(error=>console.error(error))
    }
</script>

<div class="text-center">
    <button type="submit" onclick="javascript:sendPing()">Send ping</button>
</div>
Code language: HTML, XML (xml)

2 – Before enabling CORS, verify you get a CORS error

Send the request from the browser and check the console (Dev Tools / F12) to verify that you got a CORS error. A request that fails due to a CORS error will throw a generic error like “TypeError: Failed to fetch” and then show the CORS error in the console log. It looks like this:

(X) - Access to fetch at 'https://localhost:44379/ping' from origin 'https://localhost:44395' has been blocked by CORS policy...
(X) - GET https://localhost:44379/ping net::ERR_FAILED
(X) - TypeError: Failed to fetchCode language: plaintext (plaintext)

3 – After enabling CORS, verify the request succeeds

After adding the appropriate CORS policy (I’m simply allowing ALL requests), send a request from the browser and verify that it succeeds and there’s no CORS error in the console log. The console log should look like this:

Response {type: "cors", url: "https://localhost:44379/ping", status: 200....}
Fetch finished loading: GET "https://localhost:44379/ping"Code language: plaintext (plaintext)

Leave a Comment