Live Chat Icon For mobile
Live Chat Icon

What is the purpose of the “AddDefaultPolicy” and “AddPolicy” methods in the CORS configuration?

Platform: Blazor| Category : General, Components

The AddDefaultPolicy method allows you to add a new policy to the CORS configuration and make it the application’s default. In the Startup.cs file, call the AddCors method under the ConfigureServices to add the cross-origin resource sharing services to the service collection. To add a default policy to the configuration, call the AddDefaultPolicy within the AddCors method.

[Startup.cs]

public void ConfigureServices(IServiceCollection services)
{
    ………….. . . .
    services.AddCors(options =>
    {
        options.AddDefaultPolicy (builder =>
         builder.AllowAnyOrigin()
                      .AllowAnyMethod()
                      .AllowAnyHeader());
    });
}

Since we are using the default policy, we do not need to include the policy name in the UseCors method, as shown.

[Startup.cs]

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    ………….. . . . 
    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 so that it can be identified. In the Startup.cs file, call the AddCors method under ConfigureServices to add the cross-origin resource sharing services to the service collection. To add a user-defined (custom) policy to the configuration, call AddPolicy within the AddCors method.

 [Startup.cs]

public void ConfigureServices(IServiceCollection services)
{
    …………… . . .
    services.AddCors(options =>
    {
        options.AddPolicy("NewPolicy", builder =>
         builder.WithOrigins("https://localhost:8080")
                      .AllowAnyHeader()
                      .WithMethods("GET");
    });
}

Under the Configure method in the Startup.cs file, call the UseCors method and pass the user-defined (custom) policy name to add the CORS middleware to the application pipeline.

[Startup.cs]

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    ………….. . . .
    app.UseRouting();
    app.UseCors("NewPolicy");
    app.UseAuthorization();
}

Note: Call the UseCors method between the UseRouting and UseAuthorization methods.

Share with

Share on twitter
Share on facebook
Share on linkedin

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.