Live Chat Icon For mobile
Live Chat Icon

How do you enable CORS in a Blazor Server application?

Platform: Blazor| Category : General, Components

CORS stands for cross-origin resource sharing, and it is an HTTP header-based mechanism that allows the server to tell the browser whether to accept a request from a domain, port, or scheme other than its own. It is based on a process in which the browser sends a “preflight” request to the server, and the server responds with response headers indicating whether the request can proceed or not. The browser will either succeed or fail the request based on what these headers say. The browser sends headers that indicate the HTTP method and headers that will be used in the actual request in the preflight request.

To enable CORS in your Blazor Server application, follow these steps:

  1. Create a new Blazor Server application in Visual Studio 2019 by following this link.

  2. Once the application has been created, 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 new policy to the configuration, call the AddPolicy within the AddCors method.
    [Startup.cs]

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages();
        services.AddServerSideBlazor();
        services.AddCors(options =>
        {
            options.AddPolicy("NewPolicy", builder =>
             builder.AllowAnyOrigin()
                          .AllowAnyMethod()
                          .AllowAnyHeader());
        });
    }

  3. Under the Configure method in the Startup.cs file, call the UseCors method and pass the appropriate 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.