ASP.NET Core Response Caching
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.
When to use Response Caching?
Response caching can be used to cache application items that are static, and have very less 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
HTTP Based Caching
Caches data at 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 in-proc, 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 cache. Similar to In-Memory Caching, Distributed Cache Tag Helper allow 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. 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.
Install NuGet Package
Open Package Manager Console in your Visual Studio project and install the NuGet package NCache.Microsoft.Extensions.Caching Enterprise, Professional, OpenSource in your application by executing the following command:
For Enterprise:
Install-Package NCache.Microsoft.Extensions.Caching
For Professional:
Install-Package NCache.Microsoft.Extensions.Caching.Professional
For OpenSource:
Install-Package NCache.Microsoft.Extensions.Caching.OpenSource
Reference NCache Assembly
To utilize NCache's methods for response caching, include the following namespace to your application:
using Alachisoft.NCache.Caching.Distributed;
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 Distributed Cache
NCache provides custom methods 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": "demoClusteredCache",
"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 = "demoClusteredCache";
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 cache till the query string in URL is same for the value specified in this tag.
For more detail of the parameters, refer to the Microsoft documentation for Tag Helpers before proceeding.
Once the application is executed, you can monitor the cache statistics through NCache Web Manager/NCache Monitor for Enterprise edition, or PerfMon Counters for Professional edition.
@{
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 sample application for Response caching at:
Shipped with NCache: %NCHOME%\samples\dotnetcore\ResponseCaching
See Also
Object Caching in ASP.NET Core
Multi-Region ASP.NET Core Session Provider
ASP.NET