ASP.NET – How to enable CORS for all endpoints

The simplest way to enable CORS for all endpoints is by adding a default CORS policy in the Startup class.

The following code shows the two lines of code to add:

public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { //1 - Add default CORS policy - I am simply allowing everything services.AddCors(o => o.AddDefaultPolicy(b => b.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader())); services.AddControllers(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); //2 - Adds CORS middleware. This must be placed AFTER app.UseRouting(). app.UseCors(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } }
Code language: C# (cs)

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

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 calls 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 you enable CORS, verify you get a 405 – Method Not Allowed

To be able to verify that the CORS policy works, I first have to verify that get a 405 – Method Not Allowed when the CORS policy isn’t enabled.

3 – After enabling CORS, verify your request is now allowed

I added the CORS policy to my web API. Then in my test page in the browser, I clicked the [Send ping] button and verified that this cross-origin request is now allowed.

Leave a Comment