How to Make a ASP.NET 9 API CORS Compatible? – Reliable Hosting ASP.NET Reviews
ASP.NET Hosting

How to Make a ASP.NET 9 API CORS Compatible?

Web browsers use a security mechanism called Cross-Origin Resource Sharing (CORS) to prevent web apps from sending requests to a domain other than the one that served the application. To allow requests from other origins, CORS must be explicitly enabled in.NET APIs. You will learn how to enable CORS in a.NET API from this post.
Set up CORS in the application.CS

To define and enable CORS for.NET 6 and later versions, make changes to the Program.cs file.

var builder = WebApplication.CreateBuilder(args);
// Add services to the container
builder.Services.AddControllers();
// Configure CORS policy
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowSpecificOrigins", policy =>
    {
        policy.WithOrigins("https://example.com") // Specify allowed origins
              .AllowAnyHeader()
              .AllowAnyMethod();
    });
});
var app = builder.Build();
// Enable CORS before using controllers
app.UseCors("AllowSpecificOrigins");

app.UseAuthorization();
app.MapControllers();
app.Run();

Allow All Origins (For Development Only)

If you need to allow all origins during development, modify the CORS policy as follows.

options.AddPolicy("AllowAll", builder =>
{
    builder.AllowAnyOrigin()
           .AllowAnyMethod()
           .AllowAnyHeader();
});

Then apply this policy using the app.UseCors(“AllowAll”).

Conclusion

Enabling CORS in a .NET API is essential when your front end and back end are hosted on different domains. Always restrict origins to specific trusted domains in production to maintain security. By following the steps outlined above, you can successfully configure and manage CORS in your .NET API.

ASP.NET Core 8.0.11 Hosting Recommendation

HostForLIFE.eu
HostForLIFE.eu is a popular recommendation that offers various hosting choices. Starting from shared hosting to dedicated servers, you will find options fit for beginners and popular websites. It offers various hosting choices if you want to scale up. Also, you get flexible billing plans where you can choose to purchase a subscription even for one or six months.