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:
Create a new Blazor Server application in Visual Studio 2019 by following this link.
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.
public void ConfigureServices(IServiceCollection services)
options.AddPolicy("NewPolicy", builder =>
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.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
Note: Call the UseCors method between the UseRouting and UseAuthorization methods.