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 =>
{
    options.AddPolicy("AllowSpecificOrigins",
        builder =>
        {
            builder.WithOrigins("https://abc.com", "https://xyz.com")
                   .AllowAnyHeader()
                   .AllowAnyMethod();
        });
});

builder.Services.AddControllers();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}

app.UseHttpsRedirection();

// Enable CORS
app.UseCors("AllowSpecificOrigins");

app.UseAuthorization();

app.MapControllers();

app.Run();

3. Create a Simple Controller:

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

using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class SampleController : ControllerBase
{
    [HttpGet]
    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., https://abc.com, https://xyz.com). Also, we can verify that requests are allowed or blocked based on your CORS policy configuration.

ABOUT THE AUTHOR

Techiehook
Techiehook
Admin, Australia

Welcome to TechieHook.com! 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

https://www.techiehook.com/profile/alagu-mano-sabari-m

Comments (0)

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