AddCorsPolicy
Registers a named CORS policy from the AllowedOrigins configuration array, with headers and methods from the optional AllowedHeaders and AllowedMethods arrays. Leaving either out allows any header or any method, and the policy always allows credentials, which is what a browser needs to send cookies to an API on another origin.
An absent or empty AllowedOrigins produces a policy with no origins, which blocks every cross-origin request rather than allowing them.
WARNING
Because the policy allows credentials, the * wildcard cannot be used — browsers reject that combination. A * entry throws while the CORS options are built, the first time the policy is resolved rather than during this call, instead of producing a policy that fails only in the browser.
Usage
using AlmightyShogun.AspNet.Core;
builder.Services.AddCorsPolicy("frontend", builder.Configuration);
WebApplication app = builder.Build();
app.UseCors("frontend");{
"AllowedOrigins": [
"https://app.example.com",
"https://admin.example.com"
],
"AllowedMethods": ["GET", "POST"],
"AllowedHeaders": ["Content-Type", "Authorization"]
}Parameters
name: string
Name of the CORS policy to register.
configuration: IConfiguration
Application configuration that may contain the AllowedOrigins, AllowedHeaders and AllowedMethods string arrays.
Returns
The sameIServiceCollection instance with the CORS policy configured.Type signature
public IServiceCollection AddCorsPolicy(
string name,
IConfiguration configuration
);