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.
ASP.NET supports the following types of caching:
Follow these steps to add caching to your ASP.NET application:
// 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.
// 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.
// 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.
// 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.
// 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.