Logo

dev-resources.site

for different kinds of informations.

Enabling CORS in a .NET Core Server-Side Application

Published at
12/30/2023
Categories
core
net
cors
csharp
Author
ussdlover
Categories
4 categories in total
core
open
net
open
cors
open
csharp
open
Author
9 person written this
ussdlover
open
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.

core Article's
30 articles in total
Favicon
Understanding Process Management in Operating Systems
Favicon
Introduction to Operating Systems
Favicon
What is SignalR? A Real-Time Communication Framework for .NET
Favicon
[KOSD] Change of FromQuery Model Binding from .NET 6 to .NET8
Favicon
JDK, JVM, and JRE: The Three Musketeers of Java Development πŸ‡
Favicon
Optimizing Your Development Machine: How Many Cores and Threads Do You Need for Programming?
Favicon
ASP .NET Core Best Practices
Favicon
Build Scalable Blazor CRUD Apps in 30 Minutes with Azure SQL
Favicon
The Benefits of Having More Threads than Cores: Unlocking the Power of Multi-threading in Modern Computing
Favicon
Deep Dive ASP.NET Core Middleware : Part 1
Favicon
The Purpose of Computer Processors (CPUs) and How Multiple Cores Improve Speed and Performance
Favicon
Primitive Data Types in Java
Favicon
How I Build a Scratch Proxy Server Using Node.js
Favicon
Javascript Working Mechanism
Favicon
A Journey Into the World of Programming with First Core Java Program
Favicon
[KOSD] Learning from Issues: Troubleshooting Containerisation for .NET Worker Service
Favicon
CORE WEB VITAL ISSUE
Favicon
Migrate to TLS 1.2 for Azure Blob Storage
Favicon
Keyboard input in Node.js
Favicon
Criando sua primeira aplicação console em .net
Favicon
Enabling CORS in a .NET Core Server-Side Application
Favicon
Digital Image Processing Notes
Favicon
Top Benefits of Using Core App Dashboard
Favicon
Understanding JavaScript Execution Context β€” The Key to Efficient Code
Favicon
5 Interesting Things About Strings in Java
Favicon
πŸ”’ Introducing Serial Log and Metro Log: Simplifying Your Logging Experience In .NET MAUI! πŸ“πŸš‡
Favicon
Understanding Core.js and Zone.js: Key to JavaScript Libraries
Favicon
Apitable.com Net6 Rest Api
Favicon
Custom resolve handler in Microsoft's ServiceProvider (enabling property injection)
Favicon
ASP.NET CORE REACT APP: System.InvalidOperationException: SPA default page middleware failed to return default page /index.html

Featured ones: