How to use CORS in ASP.NET Core minimal APIs

app.MapGet("/accessallowed", () => "Access to this endpoint is allowed."). RequireCors ("AllowAll");

The following piece of code shows how you can restrict access to a specific endpoint to a specific origin only in the Program.cs file.

app.MapGet("/accessrestricted", () => "Access to this endpoint is restricted."). RequireCors ("AllowSpecificOrigin");

Configure CORS before authentication

Finally, note that you must configure CORS before adding authentication middleware in the Program.cs file of your ASP.NET Core application. This is illustrated in the code snippet below.

app.UseCors("AllowSpecificOrigin");
app.UseAuthentication();
app.UseAuthorization();

Key takeaways

Whether your client or server components are in the same origin or in different origins, CORS is a great way to ensure that your ASP.NET Core minimal API endpoints remain secure and accessible. Most importantly, when using minimal APIs, you can implement CORS in your ASP.NET Core applications with minimal effort and zero boilerplate code.

Donner Music, make your music with gear
Multi-Function Air Blower: Blowing, suction, extraction, and even inflation

Leave a reply

Please enter your comment!
Please enter your name here