DEV Community

Cover image for Enable Cross-Origin requests on ASP.NET Core 3.1
pul
pul

Posted on • Updated on

Enable Cross-Origin requests on ASP.NET Core 3.1

In these days I’m working on an angular application that has .net 3.1 as a backend.

In this specific case I’m just working on frontend but I want to share with you the basic configuration you have to do if you want to allow different origins in a .net core 3.1 service.

Why? Because I always forget how to do it (🤦🏻‍♂️) so it’s a good way to take a note for the future.

Startup class setup

Enable cross origin requests is very easy, most of the setup is done in the Startup class.

First of all you have to register a named policy in the ConfigureServices method.

public void ConfigureServices(IServiceCollection services)
        {

            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

            services.AddCors(options => {
                options.AddPolicy(Startup.AllowAllCorsPolicy, builder => {
                    builder.AllowAnyHeader()
                    .AllowAnyOrigin();
                });
            });

        }
Enter fullscreen mode Exit fullscreen mode

Now you can use the newly created policy in the configure method.

You should add the middleware after the UseRouting and UseCors middleware.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {

            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseCors(Startup.AllowAllCorsPolicy);
        }
    }
Enter fullscreen mode Exit fullscreen mode

In the previous code snippet I omitted all the other configurations.

It’s not a good practice to allow any origin and headers but this could be a starting point where you can allow just specific domains or headers.

Controller class setup

Finally you have to enable the policy at controller level.

I suggest you to extend your controllers with a base controller class if you wanna apply the policy to all your routes.

[Microsoft.AspNetCore.Cors.EnableCors(Startup.AllowAllCorsPolicy)]
    public class YourBaseController<T> : ControllerBase where T : class
{

}
Enter fullscreen mode Exit fullscreen mode

More informations here:

Enable Cross-Origin Requests (CORS) in ASP.NET Core

Top comments (0)