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 Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay