ASP.NET Core Response Caching with IDistributedCache
ASP.NET Core provides Response Caching which allows you to cache the server response of a client request for future requests.
Response Caching boosts application performance as the response is served from the cache. Moreover, it takes off processing load from the servers as they do not need to process and generate a response for the same request again.
Note
For Advanced Options regarding Response Caching using dependency, go to ASP.NET Core Response Caching.
When to use Response Caching with IDistributedCache?
Response Caching can be used to cache application items that are static and have very little frequency of modification. This includes CSS/JavaScript files, media, or metadata of a webpage. Hence, instead of re-requesting the server for the content, this data can be fetched from the cache.
Response Caching Options
HTTPS-Based Caching
Caches data at the web browser's end on the client. This reduces the number of requests a client makes to the web server, as any subsequent requests will be entertained by the cache instead of the web server. However, once the response is cached in the browser, it will only expire once its assigned caching time is up, and cannot be cleared when needed.
In-Memory Caching
Caches data in the server's memory, using ASP.NET Core’s own internal caching provider. This option is more flexible for caching responses as ASP.NET Core provides Cache Tag Helper which allows adding tags to specify which view of the MVC application should be cached. Since this is InProc, you can restart the ASP.NET engine to clear the cache when required.
Distributed Caching
Caches data in-memory, if the application is hosted in a web farm. The cache is distributed across all the servers of the web farm and any server can respond to the client if requested data is available in the cache. Similar to in-memory caching, Distributed Cache Tag Helper allows specifying exact views which need to be cached. This is where NCache comes into play, as it can be used as a distributed cache for Response Caching through its IDistributedCache interface. Moreover, this extends more control to your application as the cache is scalable and items can be removed from the cache when required.
Using NCache for Response Caching
To use NCache as a distributed cache for Response Caching, NCache provides its own extension methods to configure services and middleware.
Prerequisites
- Install the following NuGet packages in your application:
- Enterprise: NCache.Microsoft.Extensions.Caching
- Professional: NCache.Microsoft.Extensions.Caching.Professional
- OpenSource: NCache.Microsoft.Extensions.Caching.OpenSource
- To utilize NCache's methods for Response Caching, include the following namespace to your application:
- The cache must be running.
- For API details refer to: AddResponseCaching.
- Make sure that the data being added is serializable.
- To ensure the operation is fail-safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
- To handle any unseen exceptions, refer to the Troubleshooting section.
Configure Response Caching Service
ASP.NET Core provides its own middleware for Response Caching. This has to be added to the service collection using the AddResponseCaching method.
Open Startup.cs of your project.
In the
ConfigureServices
method, add the following service:
public void ConfigureServices(IServiceCollection services)
{
services.AddResponseCaching();
// Remaining services here
}
Configure NCache as a Distributed Cache
NCache provides custom methods through IDistributedCache to configure itself as a distributed cache for ASP.NET applications. This requires just a cache name in NCache and any optional configurations to store the MVC content.
Method 1: Specify Cache Configuration in AppSettings.json
The cache configurations can be added as a separate section in Appsettings.json of your application. The following example adds a section NCacheSettings
which configures the cache name. You may change the name according to your registered cache.
Important
Make sure that the cache specified is running.
. . .
"NCacheSettings": {
"CacheName": "demoCache",
"EnableLogs": "True",
"ExceptionsEnabled": "True"
}
. . .
Once the cache configuration has been specified, NCache services are to be added to configure NCache as a distributed cache in the application.
Open Startup.cs of your project.
In the
ConfigureServices
method, add the following services:AddNCacheDistributedCache
extension method initializes configurations from Appsettings.json before adding the services to the container and adds NCache as the default distributed cache as an implementation ofIDistributedCache
.
public void ConfigureServices(IServiceCollection services)
{
// Add NCache services to the container
services.AddNCacheDistributedCache(Configuration.GetSection("NCacheSettings"));
}
Method 2: Specify Configuration in IOptions
Another method to specify configurations is by providing configuration settings as IOptions
.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services
services.AddMvc();
services.AddNCacheDistributedCache(configuration =>
{
configuration.CacheName = "demoCache";
configuration.EnableLogs = true;
configuration.ExceptionsEnabled = true;
});
}
Add Distributed Cache Tag Helper to View Class
Once NCache services have been configured for Response Caching, you can now specify the specific content of the controller views that you want to cache. ASP.NET Core provides Distributed Cache Tag Helper to add tags with parameters to the Views which will cache the marked content in the configured cache.
The following example adds the <distributed-cache>
tag to the content in Views -> About.cshtml with varying parameters. Upon refreshing the application, the content, Normal Item will change according to DateTime.Now
, while the tagged content will remain static as it is cached.
The
expires-after
attribute specifies the Absolute Expiration for the content. This item will be removed from the cache once 10 seconds are up. However, if the application is refreshed, the items are reloaded into the cache.The
name
attribute is the unique identifier for the cache for each instance of the tag helper.The
vary-by
attribute keeps the item in the cache till the query string in the URL is the same for the value specified in this tag.
For more detail on the parameters, refer to the Microsoft documentation for Tag Helpers before proceeding.
Once the application is executed, you can monitor the cache statistics through the NCache Management Center/NCache Monitor for Enterprise, or PerfMon Counters for Professional.
@{
ViewData["Title"] = "About";
}
<h2>@ViewData["Title"]</h2>
<h3>@ViewData["Message"]</h3>
<p> The value for this item will change everytime the application is refreshed.</p>
<div>@DateTime.Now.ToString()</div><br />
<p>The value for this item will be static and remain in the cache forever, unless cache is cleared.</p>
<distributed-cache name="Key:1" >
<div>@DateTime.Now.ToString()</div><br />
</distributed-cache>
<p>The value for this item will be static upon refreshing the application, but it will expire after 10 seconds.</p>
<distributed-cache name="Key:2" expires-after ="TimeSpan.FromSeconds(10)">
<div>@DateTime.Now.ToString()</div><br />
</distributed-cache>
<p>The value for this item will be static and will only be removed from cache if the "vary-by" value is changed.</p>
<distributed-cache name="Key:3" vary-by ="test">
<div>@DateTime.Now.ToString()</div><br />
</distributed-cache>
Additional Resources
NCache provides a sample application for Response Caching on GitHub.
See Also
.NET: Alachisoft.NCache.ResponseCaching; namespace.