Caching in .NET Core Web API
🗃️ Caching in .NET Core Web API
Caching is essential for performance and scalability in APIs. It helps reduce database access and CPU load by storing frequently used data temporarily. .NET Core supports several caching strategies:
- In-Memory Caching – Stores cache in app memory.
- Distributed Caching – Uses external services like Redis.
- Response Caching – Caches full HTTP responses.
1️⃣ In-Memory Caching
Perfect for single-server, lightweight scenarios where quick access to small datasets is needed.
🔧 Setup in Program.cs
builder.Services.AddMemoryCache();
🧑💻 Sample Controller
[ApiController]
[Route("api/[controller]")]
public class ProductController : ControllerBase
{
private readonly IMemoryCache _cache;
public ProductController(IMemoryCache cache)
{
_cache = cache;
}
[HttpGet("{id}")]
public IActionResult GetProduct(int id)
{
string cacheKey = $"Product_{id}";
if (!_cache.TryGetValue(cacheKey, out string product))
{
product = $"Product details for ID {id}";
var options = new MemoryCacheEntryOptions()
.SetAbsoluteExpiration(TimeSpan.FromMinutes(5));
_cache.Set(cacheKey, product, options);
}
return Ok(product);
}
}
📌 Example:
First call hits the database, subsequent calls serve cached data.
GET /api/product/1First call hits the database, subsequent calls serve cached data.
2️⃣ Distributed Caching (Redis)
Great for multi-server or cloud applications.
📦 Install Redis Package
Install-Package Microsoft.Extensions.Caching.StackExchangeRedis
🔧 Setup in Program.cs
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = "localhost:6379";
});
🧑💻 Sample Controller
[ApiController]
[Route("api/[controller]")]
public class OrderController : ControllerBase
{
private readonly IDistributedCache _cache;
public OrderController(IDistributedCache cache)
{
_cache = cache;
}
[HttpGet("{id}")]
public async Task GetOrder(int id)
{
string cacheKey = $"Order_{id}";
var cachedOrder = await _cache.GetStringAsync(cacheKey);
if (cachedOrder == null)
{
cachedOrder = $"Order details for ID {id}";
await _cache.SetStringAsync(cacheKey, cachedOrder,
new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)
});
}
return Ok(cachedOrder);
}
}
📌 Example:
Uses Redis to store and retrieve order data.
GET /api/order/1Uses Redis to store and retrieve order data.
3️⃣ Response Caching
This caches the entire HTTP response for a given duration.
🔧 Enable in Program.cs
builder.Services.AddResponseCaching();
app.UseResponseCaching();
🧑💻 Sample Controller
[ApiController]
[Route("api/[controller]")]
public class WeatherController : ControllerBase
{
[HttpGet]
[ResponseCache(Duration = 60)]
public IActionResult GetWeather()
{
return Ok(new { Temperature = 25, Condition = "Sunny" });
}
}
📌 Example:
The response is cached for 60 seconds.
GET /api/weatherThe response is cached for 60 seconds.
✅ Conclusion
- In-Memory Caching: Ideal for small apps or single-server deployments.
- Distributed Caching: Use Redis or similar for scale-out scenarios.
- Response Caching: Boosts performance by caching full responses.
Choose the appropriate caching strategy based on your API's scale, data volatility, and deployment model to optimize performance.
Comments
Post a Comment