DEV Community

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

Posted on • Edited on

4 1

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 =>
            {
                options.AddPolicy("CorsPolicy",
                    builder => builder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials());
            });
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.

            app.UseCors("CorsPolicy");
            app.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

The Fastest, Most Accurate API for Voice AI

Ad Image

Building an AI Agent that needs to deliver human-like conversations? | Speechmatics’ real-time ASR is available in 50 languages and can understand speech in a fraction of a second.

Try Free

Top comments (0)

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay