IConfiguration vs IOptions NET
Synchronous and Asynchronous in .NET Core
Model Binding and Validation in ASP.NET Core
ControllerBase vs Controller in ASP.NET Core
ConfigureServices and Configure methods
IHostedService interface in .NET Core
ASP.NET Core request processing
| Versioning WEB API in .net core | Rate Limiting in .NET Core | |
🧠 Caching in .NET Core |
Caching is a technique used to store frequently accessed data in memory to reduce latency and improve performance. In .NET Core, caching can be implemented using in-memory caching, distributed caching, or response caching.
In ASP.NET Core, caching is a powerful technique for storing frequently accessed data to improve application performance and reduce database load. ASP.NET Core provides several caching options, with the two most common being in-memory and distributed caching.
(Cache-Control, Vary) to cache full HTTP responses. This can be configured with middleware or attributes. Caches HTTP responses to reduce processing time for repeated requests.This example shows how to use IMemoryCache to cache a list of products in a web API.
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using System.Collections.Generic;
namespace CachingExample.Controllers;
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
private readonly IMemoryCache _cache;
private readonly ILogger<ProductsController>
_logger;
public ProductsController(IMemoryCache cache, ILogger<ProductsController>
logger)
{
_cache = cache;
_logger = logger;
}
[HttpGet]
public async Task<ActionResult<IEnumerable<string>>> Get()
{
string cacheKey = "all_products";
List <string>? products;
// Check if data is in cache
if (!_cache.TryGetValue(cacheKey, out products))
{
_logger.LogInformation("Cache miss. Fetching products from source.");
// Simulate fetching data from a slow data source
await Task.Delay(2000);
products = new List<string>
{ "Laptop", "Mouse", "Keyboard" }
;
// Configure cache options
var cacheOptions = new MemoryCacheEntryOptions()
.SetAbsoluteExpiration(TimeSpan.FromMinutes(5)) // Cache will expire in 5 minutes
.SetSlidingExpiration(TimeSpan.FromMinutes(2)); // Reset expiry if accessed within 2 minutes
// Store data in cache
_cache.Set(cacheKey, products, cacheOptions);
}
else
{
_logger.LogInformation("Cache hit. Serving products from cache.");
}
return Ok(products);
}
}
IMemoryCache for simple scenarios and IDistributedCache for scalable setups. | Versioning WEB API in .net core | Rate Limiting in .NET Core | |