DEV Community

Cover image for Enabling CORS in a .NET Core Server-Side Application
Alireza Razinejad
Alireza Razinejad

Posted on

9

Enabling CORS in a .NET Core Server-Side Application

Step 1: Install the Microsoft.AspNetCore.Cors NuGet Package

Open your .NET Core project in Visual Studio or your preferred code editor. In the Package Manager Console or the terminal, run the following command to install the CORS package:

dotnet add package Microsoft.AspNetCore.Cors
Enter fullscreen mode Exit fullscreen mode

Alternatively, you can use the NuGet Package Manager in Visual Studio to search for and install the package.

Step 2: Configure CORS in Startup.cs

Open the Startup.cs file in your project. In the ConfigureServices method, add the CORS policy configuration using the AddCors method:

public void ConfigureServices(IServiceCollection services)
{
    // Other ConfigureServices configurations...

    services.AddCors(options =>
    {
        options.AddPolicy("AllowSpecificOrigin",
            builder =>
            {
                builder.WithOrigins("http://example.com") // Add your client-side application's origin here
                       .AllowAnyHeader()
                       .AllowAnyMethod();
            });
    });

    // More ConfigureServices configurations...
}
Enter fullscreen mode Exit fullscreen mode

Make sure to replace "http://example.com" with the actual origin of your client-side application. If you want to allow any origin, you can use builder.AllowAnyOrigin() instead.

Step 3: Apply CORS Middleware in the Configure Method

In the Configure method of Startup.cs, add the CORS middleware using the UseCors method:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // Other Configure configurations...

    app.UseCors("AllowSpecificOrigin");

    // More Configure configurations...
}
Enter fullscreen mode Exit fullscreen mode

This middleware should be placed before any other middleware or routing configurations.

Step 4: Run and Test Your Application

Now that CORS is configured, run your .NET Core application. Make requests from your client-side application to the server and verify that CORS is working as expected.

Additional Tips:
For development purposes, you might want to install the Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet package and configure JSON serialization to allow circular references using AddNewtonsoftJson in the ConfigureServices method.

services.AddMvc().AddNewtonsoftJson(options =>
{
    options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
Enter fullscreen mode Exit fullscreen mode

Remember to handle CORS settings carefully in a production environment, and only allow specific origins that are necessary for security reasons.

Image of Stellar post

How a Hackathon Win Led to My Startup Getting Funded

In this episode, you'll see:

  • The hackathon wins that sparked the journey.
  • The moment José and Joseph decided to go all-in.
  • Building a working prototype on Stellar.
  • Using the PassKeys feature of Soroban.
  • Getting funded via the Stellar Community Fund.

Watch the video

Top comments (0)

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay