DEV Community

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

Posted on

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.

Top comments (0)