Caching in .NET Core Web API
Caching in .NET Core Web API
Caching is a crucial technique to
improve the performance and scalability of a web API by reducing database calls
and computational load. .NET Core provides built-in caching mechanisms, such
as in-memory caching, distributed caching, and response
caching. This article will cover different caching strategies with
real-world examples.
Types of Caching in .NET Core Web
API
- In-Memory Caching –
Stores data in the application's memory for quick access.
- Distributed Caching –
Stores data in external systems like Redis for scalability.
- Response Caching –
Caches HTTP responses to improve performance.
1. In-Memory Caching
In-Memory Caching is
best suited for storing frequently accessed data within a single instance of an
application.
Step 1: Install the Required
Package
The required package comes with
.NET Core, so no additional installation is needed.
Step 2: Configure Caching in
Program.cs
using
Microsoft.Extensions.Caching.Memory;
var builder =
WebApplication.CreateBuilder(args);
builder.Services.AddMemoryCache();
var app = builder.Build();
Step 3: Implement In-Memory
Caching in 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 cacheEntryOptions = new MemoryCacheEntryOptions()
.SetAbsoluteExpiration(TimeSpan.FromMinutes(5));
_cache.Set(cacheKey, product, cacheEntryOptions);
}
return Ok(product);
}
}
Example API Request
GET /api/product/1
First request:
Fetches from database. Subsequent requests: Fetches from cache.
2. Distributed Caching (Using
Redis)
Distributed caching is useful for
applications running on multiple servers.
Step 1: Install Redis Package
Install-Package
Microsoft.Extensions.Caching.StackExchangeRedis
Step 2: Configure Redis in
Program.cs
var builder =
WebApplication.CreateBuilder(args);
builder.Services.AddStackExchangeRedisCache(options
=>
{
options.Configuration = "localhost:6379";
});
var app = builder.Build();
Step 3: Implement Redis Caching in
Controller
using
Microsoft.Extensions.Caching.Distributed;
using System.Text;
[ApiController]
[Route("api/[controller]")]
public class OrderController :
ControllerBase
{
private
readonly IDistributedCache _cache;
public
OrderController(IDistributedCache cache)
{
_cache = cache;
}
[HttpGet("{id}")]
public async
Task<IActionResult> 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 API Request
GET /api/order/1
3. Response Caching
Response caching stores the
response of an HTTP request and serves it without re-processing.
Step 1: Enable Response Caching in
Program.cs
var builder =
WebApplication.CreateBuilder(args);
builder.Services.AddResponseCaching();
var app = builder.Build();
app.UseResponseCaching();
Step 2: Implement Response Caching
in Controller
[ApiController]
[Route("api/[controller]")]
public class WeatherController :
ControllerBase
{
[HttpGet]
[ResponseCache(Duration = 60)]
public
IActionResult GetWeather()
{
return Ok(new { Temperature = 25, Condition = "Sunny" });
}
}
Example API Request
GET /api/weather
Response is cached for 60
seconds.
Conclusion
- Use In-Memory Caching for
small, frequently accessed data.
- Use Distributed Caching (Redis) for
large-scale applications.
- Use Response Caching to
cache HTTP responses efficiently.
Implementing caching improves API
performance by reducing database queries and response times.
Comments
Post a Comment