.NET 8: How to make API faster in Asp.Net Core

Developing a Web API is a common task in Web development and Mobile Apps, but improving the performance of API is the real challenge. In this article, we will explore How to make API faster in .NET 8 Asp.Net Core using Distributed Caching (Redis).

Why Redis Cache?

Before we implementation of  Redis Cache, let’s understand why we need Redis Cache. In any application, fetching data from the database or any other different resources is a time-consuming process. To improve this, we use caching.

Redis Cache stores the frequently accessed data in-memory and retrieves it at a much faster rate compared to traditional databases.

Create an Asp.NET Core Web API Project

Assuming you have Visual Studio 2019 or Visual Studio 2022 installed, follow these steps to create a new ASP.NET Core Project

  • Open the visual studio (IDE).
  • Click on the “Create new project” option.
  • Choose “ASP.NET Core Web API” from the list of available templates.
  • Click the Next button.
  • The configure a new project, specify the name and location of your project.
  • Click the “Next” button.
  • Then select .Net Core as the runtime and choose the version from the dropdown list at the top.
  • Make sure to uncheck the checkboxes for “Enable Docker Support” and “Configure for HTTPS” since we won’t be using authentication.
  • Click the “Create” button

Install Redis

Install Redis Cache using NuGet Package or run the following command in Package Manager Console.

Implement distributed Caching?

Open the Program.cs file and configure.

using dotNet8CRUDWebAPI.Services;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();

builder.Services.AddOutputCache(option => option.DefaultExpirationTimeSpan = TimeSpan.FromMinutes(10))
    .AddStackExchangeRedisCache(opt =>
    {
        opt.InstanceName = "TodosWebAPI";
        opt.Configuration = "localhost";
    }
    );


var app = builder.Build();

// Configure the HTTP request pipeline.

app.UseOutputCache();
app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

Create a Model

namespace dotNet8CRUDWebAPI.Model
{
    public class TodoUserList
    {
        public int userId {  get; set; }
        public int id { get; set; }
        public string title { get; set; }
        public bool completed { get; set; }
    }
}

Create a Controller

Open the controller create action method and Add the [OutputCache] attribute.

using dotNet8CRUDWebAPI.Model;
using dotNet8CRUDWebAPI.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OutputCaching;

namespace dotNet8CRUDWebAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class DepartmentController : ControllerBase
    {

        [HttpGet("GetDatafromOtherSource")]
        [OutputCache]
        public async Task<IActionResult> GetDatafromOtherSource()
        {
            using var httpClient = new HttpClient();
            var response = await httpClient.GetFromJsonAsync<TodoUserList[]>("https://jsonplaceholder.typicode.com/todos");
            return Ok(response); 
        }
    }
}

Now simply run the application or press F5 to run

As you can see, caching has allowed us to reduce the response time all the way down to 1.2 s.  that’s all I have to say for now, I hope you found this information helpful.

See More: .NET 8: ASP.Net Core Web API CRUD Operations

Leave a Reply

Your email address will not be published. Required fields are marked *