The AddDefaultPolicy method allows you to add a new policy to the CORS configuration and make it the application’s default. In the Program.cs file, you can call the AddCors method to add the cross-origin resource sharing services to the service collection. To add a default policy to the configuration, you can call the AddDefaultPolicy within the AddCors method. Since you are using the default policy, there is no need to include the policy name in the UseCors method, as shown.
[Program.cs]
….
builder.Services.AddCors(options =>
{
options.AddDefaultPolicy("NewPolicy", builder =>
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
….
app.UseRouting();
app.UseCors();
app.UseAuthorization();
The AddPolicy method allows you to add a custom policy to the CORS configuration and give it a name for identification. In the Program.cs file, to add a user-defined (custom) policy to the configuration, you can call AddPolicy within the AddCors method.
[Program.cs]
builder.Services.AddCors(options =>
{
options.AddPolicy("NewPolicy", builder =>
builder.WithOrigins("https://localhost:8080")
.AllowAnyHeader()
.WithMethods("GET"));
});
Then, you should call the UseCors method and pass the user-defined (custom) policy name to add the CORS middleware to the application pipeline.
[Progaram.cs]
app.UseRouting();
app.UseCors("NewPolicy");
app.UseAuthorization();
Note: Call the UseCors method between the UseRouting and UseAuthorization methods.
Share with