.NET Learning Notes: CORS and how to deal with it in developing

CORS Cross-Origin Resource Sharing is a mechanism that uses HTTP headers to grant a web application running on one origin permission to reach selected resources in a different origin.The web application executes a cross-origin HTTP request when it requests a resource that has a different origin from its own, including domain, protocol, or port. How to fix it in .NET Bacause the frontend port in my VS Code always change, I can not hardcode origins. var builder = WebApplication.CreateBuilder(args); // Add CORS service with dynamic origin checking builder.Services.AddCors(options => { options.AddPolicy("DynamicCors", policy => { policy .SetIsOriginAllowed(origin => origin.StartsWith("http://localhost:")) // allow all localhost ports .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); // if you're sending cookies or auth headers }); }); var app = builder.Build(); // Enable the CORS middleware app.UseCors("DynamicCors"); app.UseAuthorization(); app.MapControllers(); app.Run(); Notes: SetIsOriginAllowed(origin => origin.StartsWith("http://localhost:")) lets any localhost port access your backend during development. Do not use AllowAnyOrigin() with AllowCredentials() — it's invalid per the CORS spec. This only applies during development. In production, you should restrict to known origins.

Apr 29, 2025 - 13:07
 0
.NET Learning Notes: CORS and how to deal with it in developing

CORS
Cross-Origin Resource Sharing is a mechanism that uses HTTP headers to grant a web application running on one origin permission to reach selected resources in a different origin.The web application executes a cross-origin HTTP request when it requests a resource that has a different origin from its own, including domain, protocol, or port.

How to fix it in .NET
Bacause the frontend port in my VS Code always change, I can not hardcode origins.

var builder = WebApplication.CreateBuilder(args);

// Add CORS service with dynamic origin checking
builder.Services.AddCors(options =>
{
    options.AddPolicy("DynamicCors", policy =>
    {
        policy
            .SetIsOriginAllowed(origin => origin.StartsWith("http://localhost:")) // allow all localhost ports
            .AllowAnyHeader()
            .AllowAnyMethod()
            .AllowCredentials(); // if you're sending cookies or auth headers
    });
});

var app = builder.Build();

// Enable the CORS middleware
app.UseCors("DynamicCors");

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

Notes:

  • SetIsOriginAllowed(origin => origin.StartsWith("http://localhost:")) lets any localhost port access your backend during development.

  • Do not use AllowAnyOrigin() with AllowCredentials() — it's invalid per the CORS spec.

  • This only applies during development. In production, you should restrict to known origins.