Learn extra at:
app.MapGet("/accessallowed", () => "Entry to this endpoint is allowed."). RequireCors ("AllowAll");
The next piece of code exhibits 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, observe that it’s essential 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 consumer or server elements are in the identical origin or in numerous 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’ll be able to implement CORS in your ASP.NET Core purposes with minimal effort and 0 boilerplate code.