ASP.NET Tutorial : Techniques for Caching in ASP.NET Core

Leave a Comment

Caching is a crucial strategy for enhancing ASP.NET Core applications' responsiveness and speed. To store and retrieve data efficiently, developers can leverage a variety of caching mechanisms provided by ASP.NET Core. Some ASP.NET Core caching techniques are listed below:

Caching in-Memory
Data is temporarily stored in the application's memory through in-memory caching.
useful for keeping somewhat static and often accessible data.

services.AddMemoryCache();

Usage in a controller

private readonly IMemoryCache _memoryCache;

public MyController(IMemoryCache memoryCache)
{
    _memoryCache = memoryCache;
}

public IActionResult MyAction()
{
    var cachedData = _memoryCache.GetOrCreate("CacheKey", entry =>
    {
        entry.SlidingExpiration = TimeSpan.FromMinutes(10);
        return GetDataFromDatabase();
    });

    return View(cachedData);
}
Distributed Caching
  • Distributed caching stores data across multiple servers to share cached data among different instances of the application.
  • Suitable for scenarios where the application is hosted on a web farm or in a cloud environment.

Example using Redis

services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = "localhost:6379"; // Redis server connection string
    options.InstanceName = "SampleInstance";
});

Usage is similar to in-memory caching but with the distributed cache provider.

Response Caching
  • Response caching caches the entire HTTP response, including headers and content, at the server or client side.
  • Helps reduce the load on the server and improve client-side performance.

Example in Startup.cs

services.AddResponseCaching();

Usage in a controller or action method:

[ResponseCache(Duration = 60, Location = ResponseCacheLocation.Any)]
public IActionResult MyAction()
{
    return View();
}
Output Caching
  • Output caching caches the output of a controller action or Razor page.
  • Helps reduce the processing time of the same request repeatedly.

Example in a controller

[ResponseCache(Duration = 60, VaryByQueryKeys = new[] { "id" })]
public IActionResult MyAction(int id)
{
    return View(GetDataById(id));
}

Donut Caching
  • Donut caching is a combination of output caching and donut hole caching, where you can cache parts of a page independently.
  • Useful for caching specific sections of a page.

Example using TagHelper

<cache expires-after="@TimeSpan.FromMinutes(10)">
    <!-- Cached content here -->
</cache>
Conclusion

These caching strategies can be used individually or in combination based on the application's requirements. It's important to carefully choose the appropriate caching strategy considering factors such as data volatility, scalability, and caching granularity. Additionally, always monitor and adjust cache expiration times to ensure the cached data remains relevant.

Windows Hosting Recommendation

HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 7.0.10 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Next PostNewer Post Previous PostOlder Post Home

0 comments:

Post a Comment