Here's an example of how you can implement server-side caching in ASP.NET to improve performance:
public ActionResult Index()
{
// Try to get the data from cache
var cachedData = HttpContext.Cache["CachedData"] as List<MyData>;
if (cachedData == null)
{
// Data is not in cache, so fetch it from the database or another source
cachedData = GetDataFromDatabase();
// Store the data in cache with a sliding expiration of 5 minutes
HttpContext.Cache.Insert("CachedData", cachedData, null, DateTime.Now.AddMinutes(5), TimeSpan.Zero);
}
return View(cachedData);
}
In this example, we're using the HttpContext.Cache
object to store and retrieve data from the server-side cache. Here's what the code does:
- First, it tries to retrieve the data from the cache using the key "CachedData".
- If the data is found in the cache (
cachedData != null
), it is used directly. - If the data is not found in the cache, it fetches the data from the database or another source (
GetDataFromDatabase()
). - The fetched data is then stored in the cache using the
HttpContext.Cache.Insert
method. It specifies a sliding expiration of 5 minutes, meaning that if the data is not accessed within 5 minutes, it will be removed from the cache. - Finally, the data (either retrieved from the cache or fetched from the source) is passed to the view for rendering.
By implementing server-side caching, you can avoid unnecessary database or source calls and improve the performance of your ASP.NET application.
Comments
Post a Comment