Implementing Caching in .NET Core Web API


Caching is one of the most effective ways to improve the performance and scalability of your APIs. By storing frequently requested data, you can reduce database load, speed up response times, and handle higher traffic without degrading performance.

In this article, we’ll explore memory caching, response caching, and distributed caching in .NET Core Web API with practical examples.




1. Response Caching

Response caching allows responses from your API to be stored and reused for a specified duration.



Setup in Program.cs

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddResponseCaching();
var app = builder.Build();
app.UseResponseCaching();
app.MapControllers();
app.Run();
Enter fullscreen mode

Exit fullscreen mode



Using Response Caching in Controller

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    [HttpGet]
    [ResponseCache(Duration = 60, Location = ResponseCacheLocation.Client)]
    public IActionResult Get()
    {
        var products = new[] { "Product 1", "Product 2" };
        return Ok(products);
    }
}
Enter fullscreen mode

Exit fullscreen mode

✅ The API response will be cached for 60 seconds on the client.




2. In-Memory Caching

In-memory caching stores data in the server’s memory.



Setup in Program.cs

builder.Services.AddMemoryCache();
Enter fullscreen mode

Exit fullscreen mode



Using In-Memory Cache in Controller

[ApiController]
[Route("api/[controller]")]
public class OrdersController : ControllerBase
{
    private readonly IMemoryCache _cache;

    public OrdersController(IMemoryCache cache)
    {
        _cache = cache;
    }

    [HttpGet]
    public IActionResult GetOrders()
    {
        const string cacheKey = "orders_list";
        if (!_cache.TryGetValue(cacheKey, out string[] orders))
        {
            // Simulate fetching from database
            orders = new[] { "Order 1", "Order 2" };

            var cacheOptions = new MemoryCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5),
                SlidingExpiration = TimeSpan.FromMinutes(2)
            };

            _cache.Set(cacheKey, orders, cacheOptions);
        }

        return Ok(orders);
    }
}
Enter fullscreen mode

Exit fullscreen mode

✅ Reduces repeated database calls for frequently accessed data.




3. Distributed Caching

Distributed caching stores cache outside of the application, suitable for multi-server environments.



Setup with Redis

dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis
Enter fullscreen mode

Exit fullscreen mode

builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = "localhost:6379";
    options.InstanceName = "MyApp_";
});
Enter fullscreen mode

Exit fullscreen mode



Using Distributed Cache in Controller

[ApiController]
[Route("api/[controller]")]
public class CustomersController : ControllerBase
{
    private readonly IDistributedCache _cache;

    public CustomersController(IDistributedCache cache)
    {
        _cache = cache;
    }

    [HttpGet]
    public async Task<IActionResult> GetCustomers()
    {
        var cacheKey = "customers_list";
        var cachedData = await _cache.GetStringAsync(cacheKey);

        if (string.IsNullOrEmpty(cachedData))
        {
            var customers = new[] { "Customer 1", "Customer 2" };
            cachedData = System.Text.Json.JsonSerializer.Serialize(customers);
            var options = new DistributedCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)
            };

            await _cache.SetStringAsync(cacheKey, cachedData, options);
        }

        var result = System.Text.Json.JsonSerializer.Deserialize<string[]>(cachedData);
        return Ok(result);
    }
}
Enter fullscreen mode

Exit fullscreen mode

✅ Works across multiple instances of your API in a load-balanced environment.




Wrapping Up

Caching is essential for improving API performance, scalability, and user experience. In .NET Core Web API, you have several options:

  • Response Caching: For simple, client-side caching of responses.
  • In-Memory Caching: Quick caching within a single server instance.
  • Distributed Caching: Scalable caching across multiple servers (e.g., Redis).

By implementing caching appropriately, you can drastically reduce database load and improve response times for your users.



Source link

Leave a Reply

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