Caching Techniques in ASP.NET

What is Caching?

Caching is a technique to store data temporarily so that future requests for the same data can be served faster. In ASP.NET, caching helps improve application performance by reducing database queries and computation time.

  • Improves Performance: Frequently accessed data is retrieved faster.
  • Reduces Server Load: Avoids repetitive database or external API calls.
  • Enhances User Experience: Faster response times for end users.

Types of Caching in ASP.NET

ASP.NET supports the following types of caching:

  • In-Memory Caching: Stores data in the server's memory.
  • Distributed Caching: Stores data in an external cache like Redis for scalability.
  • Response Caching: Caches HTTP responses to improve client-side performance.

How to Implement Caching in ASP.NET

Follow these steps to add caching to your ASP.NET application:

1. Set Up In-Memory Caching


// Program.cs
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddMemoryCache(); // Register in-memory cache
builder.Services.AddControllers();

var app = builder.Build();

app.MapControllers();

app.Run();

                

The AddMemoryCache method registers in-memory caching services.

2. Cache Data in a Controller


// Controllers/ProductController.cs
[ApiController]
[Route("api/products")]
public class ProductController : ControllerBase
{
    private readonly IMemoryCache _cache;

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

    [HttpGet]
    public IActionResult GetProducts()
    {
        const string cacheKey = "products";
        if (!_cache.TryGetValue(cacheKey, out List<string> products))
        {
            // Simulate fetching data from a database
            products = new List<string> { "Laptop", "Smartphone", "Tablet" };

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

            _cache.Set(cacheKey, products, cacheOptions);
        }
        return Ok(products);
    }
}

                

The TryGetValue method checks if data is already in the cache. If not, the data is added with specific cache options.

3. Use Distributed Caching with Redis


// Program.cs
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = "localhost:6379"; // Redis server address
});
builder.Services.AddControllers();

var app = builder.Build();

app.MapControllers();

app.Run();

                

The AddStackExchangeRedisCache method configures Redis for distributed caching.

4. Cache Responses Using Response Caching


// Program.cs
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddResponseCaching();
builder.Services.AddControllers();

var app = builder.Build();

app.UseResponseCaching();
app.MapControllers();

app.Run();

                

// Controllers/HomeController.cs
[ApiController]
[Route("api/home")]
public class HomeController : ControllerBase
{
    [HttpGet]
    [ResponseCache(Duration = 60)]
    public IActionResult Get()
    {
        return Ok(new { Message = "Hello, Cached World!", Time = DateTime.Now });
    }
}

                

The [ResponseCache] attribute caches the HTTP response for a specified duration.

5. Test Your Caching Implementation


// Test In-Memory Cache
GET /api/products
Response: ["Laptop", "Smartphone", "Tablet"]

// Test Response Cache
GET /api/home
Response: { "Message": "Hello, Cached World!", "Time": "2024-11-24T12:00:00Z" }

                

Use tools like Postman to verify the caching behavior.