What is Caching in ASP.NET Core? See Example

Caching in ASP.NET Core is a technique to store frequently used data temporarily to improve application performance. It reduces database calls and speeds up response times. ASP.NET Core supports in-memory caching, distributed caching, and response caching.

Key Features:

  • Improves app performance and reduces latency
  • Supports in-memory and distributed caches
  • Can cache responses, data, or computed results
  • Easy integration with MVC, Razor Pages, and Web API
  • Configurable expiration and sliding policies

Example:
In-memory caching in a controller:

public class HomeController : Controller
{
    private readonly IMemoryCache _cache;
    public HomeController(IMemoryCache cache)
    {
        _cache = cache;
    }

    public IActionResult Index()
    {
        if(!_cache.TryGetValue("Time", out string currentTime))
        {
            currentTime = DateTime.Now.ToString();
            _cache.Set("Time", currentTime, TimeSpan.FromMinutes(5));
        }
        return Content($"Current Time: {currentTime}");
    }
}

Caching in ASP.NET Core helps reduce server load, enhance performance, and improve user experience.

Citations:

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *