app.MapGet("/accessallowed", () => "Entry to this endpoint is allowed."). RequireCors ("AllowAll");
The next piece of code reveals how one can prohibit entry to a selected endpoint to a selected origin solely within the Program.cs file.
app.MapGet("/accessrestricted", () => "Entry to this endpoint is restricted."). RequireCors ("AllowSpecificOrigin");
Configure CORS earlier than authentication
Lastly, notice that you have to configure CORS earlier than including authentication middleware within the Program.cs file of your ASP.NET Core software. That is illustrated within the code snippet beneath.
app.UseCors("AllowSpecificOrigin");
app.UseAuthentication();
app.UseAuthorization();
Key takeaways
Whether or not your shopper or server parts are in the identical origin or in several origins, CORS is an effective way to make sure that your ASP.NET Core minimal API endpoints stay safe and accessible. Most significantly, when utilizing minimal APIs, you may implement CORS in your ASP.NET Core purposes with minimal effort and 0 boilerplate code.