Techiehook Techiehook
Updated date Jul 03, 2024
In this article, we will learn how to configure Cross-Origin Resource Sharing (CORS) in ASP.NET Core (.NET 8) to allow secure communication between client-side web applications and APIs.

Implementing CORS in ASP.NET Core:

Handling CORS (Cross-Origin Resource Sharing) in ASP.NET Core (including .NET 8) involves configuring the CORS policy in your application to allow or restrict requests from specified origins.

Below are the steps to implement the CORS in ASP.NET Core,

1. Install the required package:

We need to include the CORS package in our project. This is usually included by default in ASP.NET Core projects, but you can add it explicitly if needed.

install-package Microsoft.AspNetCore.Cors

2. Configure CORS in Program.cs:

We can open the Program.cs file and configure the CORS policy as shown below.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddCors(options =>
        builder =>
            builder.WithOrigins("", "")


var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())


// Enable CORS




3. Create a Simple Controller:

We will create a simple controller to test the CORS configuration:

using Microsoft.AspNetCore.Mvc;

public class SampleController : ControllerBase
    public IActionResult Get()
        return Ok("Test Controller - CORS enabled!");

4. Run and Test the Application:

We can create a simple HTML page with JavaScript to send requests to our API from different origins (e.g.,, Also, we can verify that requests are allowed or blocked based on your CORS policy configuration.


Admin, Australia

Welcome to! We are all about tech, lifestyle, and more. As the site admin, I share articles on programming, tech trends, daily life, and reviews... For more detailed information, please check out the user profile

Comments (0)

There are no comments. Be the first to comment!!!