ASP.NET Core Response Caching
Note
This feature is for NCache Enterprise only.
ASP.NET Core provides response caching which allows you to cache the server response of a client request for future requests.
Advanced Response Caching Options
Note
This feature is only available in NCache 5.2
- Database Dependency
NCache lets you add database dependency to the response cached in NCache. The database can either be:
- Microsoft SQL Server or
- Oracle Server
By adding database dependency to any page, any change in the database removes the page from the cache. This keeps the cache data synced with the data in the database.
- Data Invalidation
Another technique provided by NCache to keep the cache data fresh and throwing the stale data out of the cache is data invalidation. Whenever application data changes, the application needs to take care of its web representation as out of date. If a response is cached and at any time the data is changed on that page, which affects the other data, the cache is forced to fetch new and fresh data. For example, on successfully removing an item from your shopping cart in an e-commerce website, the shopping cart needs to reflect the changes made thus invalidating the data. An invalidation tag is added with the observable data and is responsible for removing the invalid or stale data from the cache. New data is then fetched from the database against the invalidated data. With data invalidation tag set true for success pages on data update, any response cached in the cache is invalidated to get a fresh response from the cache.
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 in your application by executing the following command:
For Enterprise:
Install-Package Alachisoft.NCache.ResponseCaching
Reference NCache Assembly
To utilize NCache's methods for response caching, include the following namespace to your application:
using Alachisoft.NCache.ResponseCaching;
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. We specify the following method for configuration.
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. After adding the cache name, you can provide the default connection string name which contains the name of the connection string for making connection with the server for adding the database dependency. In case of multiple connection strings for multiple databases, the default connection string decides which database name to use. Each connection string should have a name as shown below.
Important
Make sure that the cache specified is running.
. . .
"NCacheSettings": {
"CacheName": "demoClusteredCache",
"EnableLogs": "True",
"ExceptionsEnabled": "True"
"DefaultConnectionStringName": "DBServer1"
},
"ConnectionStrings": {
"DBServer1": "Data Source=20.20.20.10\\SQLEXPRESS;Database=Northwind;User Id=admin;password=xxxxxxxx"
}
. . .
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:AddOptions().Configure<NCacheConfiguration>
extension method gets called at runtime. You can use this method to add services to the container.AddNCacheResponseCachingServices()
extension method initializes the configurations related to database dependency and invalidation from Appsettings.json.
public void ConfigureServices(IServiceCollection services)
{
//Read NCache specific configurations from app.settings.json
services.AddOptions().Configure<NCacheConfiguration>(Configuration.GetSection("NCacheSettings"));
//Register NCache for response caching with dependency or invalidation
services.AddNCacheResponseCachingServices();
}
Add Distributed Cache NCache Tag Helper to View Class
As mentioned earlier, for adding database dependency with the data in the cache, a tag <distributed-cache-ncache>
is used to specify the parameters. This tag is derived from the distributed tag helper class and inherits the attributes of this class. Please follow this documentation to get a detailed information of the attributes that can be specified.
NCache provides the following attributes in this class for adding dependency:
<name>
: The key of the item which is in the cache as a unique identifier.<depends-on>
: A query which selects the items from the database on which the response is dependent. The query format contains the parameter name which is a variable redirecting to the cached response. The parameter name can be case sensitive but it should be consistent to the parameter name in the cached response. Similarly for parameterized queries, "@@" is added before the parameter name. For example, if the dependency is added on the Person ID then the parameter name should be consistent on the dependent as well as response pages.<dependency-type>
: It defines which type of database dependency is associated i.e Oracle or SQL server.
Note
You can also add the default connection string name in this tag. In case no default connection string is added here, the default connection string mentioned in the appsettings.json are used.
<dependency type: "SQLServer" connection-string-name="DBServer">
<invalidates>
: A boolean flag which is set true if invalidation is added with an attribute. On setting the flag true, on any change occurring in the dependent item, all the pages related to that key are invalidated.
Given below is a sample file that shows SQL dependency added with a response:
<distributed-cache-ncache name="key1" depends-on="Select * from products where @@id" connection-string-name="[connection_string_name] dependency-type="SQLServer|Oracle" invalidates="true">
<div>@DateTime.Now.ToString()</div><br />
</distributed-cache-ncache>
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 on GitHub.
See Also
Object Caching in ASP.NET Core
Multi-Region ASP.NET Core Session Provider
ASP.NET