DEV Community

Cover image for Enabling CORS in Dotnet Core
Arjun Shetty
Arjun Shetty

Posted on • Updated on

Enabling CORS in Dotnet Core

CORS - Cross Origin Resource Sharing, basically helps our application from Cross site scripting attacks. This will restrict a website from access or sending data to another origin( web app).

This post will help look into enabling CORS in dotnet core application. Every POST request before posting the actual requests will send an Preflighted requests using the OPTION method like the below sample.

            OPTIONS {{apiendpoint}}/api/web/incoming HTTP/1.1
            Access-Control-Request-Method: POST
            Origin: http://localhost:4200
Enter fullscreen mode Exit fullscreen mode

This is to check if the actual request method in this case POST is allowed or not.

So to enable this in dotnet core we use AddCors of the IServiceCollection in StartUp.cs like below.

            services.AddCors(options =>
                    builder => builder.AllowAnyOrigin()
Enter fullscreen mode Exit fullscreen mode

We have created the policy as per our requirements now need to use this in our MVC application, make sure you add UseCors before UseMvc.

Enter fullscreen mode Exit fullscreen mode

Now your application CORS enabled. This approach is to add CorsPolicy globally. you also refer this guide to enable CORS using attributes.

  • Photo by Banter Snaps on Unsplash

  • originally posted on BitsMonkey

Top comments (0)