Configuring CORS via IIS web.config
When hosting an ASP.NET Core application on Internet Information Services (IIS), you can manage Cross-Origin Resource Sharing (CORS) settings directly through the web.config file. This approach is effective when you want the web server to handle preflight requests and header injections before they reach the application logic.
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="https://myapp-client.com" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
<add name="Access-Control-Allow-Headers" value="Content-Type, Authorization, X-Requested-With" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
</httpProtocol>
</system.webServer>
Implementing CORS Middleware in ASP.NET Core
During local development or when you require more granular control over security policies, implementing CORS via the ASP.NET Core middleware is the standard approach. This involves two steps: defining a policy in the service container and applying that policy to the request pipeline.
1. Defining the Policy
In your Program.cs or Startup.cs, use the AddCors method to register specific policies. Depending on your security requirements, you can opt for a restrictive or permissive configuration.
// Example 1: Comprehensive policy allowing credentials
builder.Services.AddCors(cfg =>
{
cfg.AddPolicy("WebAppPolicy", policy =>
{
policy.WithOrigins("http://localhost:3000")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
// Example 2: Restricted policy without specific methods
builder.Services.AddCors(cfg =>
{
cfg.AddPolicy("RestrictedDevPolicy", policy =>
{
policy.WithOrigins("http://localhost:3000")
.AllowAnyHeader();
});
});
2. Applying the Middleware
Once the policy is defined, it must be activated within the application's request processing pipeline. Ensure that UseCors is called after UseRouting but before UseAuthorization and any endpoint mappings.
var app = builder.Build();
// Ensure the name matches the string defined in AddPolicy
app.UseCors("WebAppPolicy");
app.MapControllers();
app.Run();
When troubleshooting CORS issues in a local environment, verify that the origin URL (including the protocol and port) exactly matches the URL of your front-end application. If the browser still blocks requests, check if multiple layers (such as both IIS and the aplication code) are trying to set the same CORS headers simultaneously, which can cause conflicts.