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.
Note
This feature is available in NCache Enterprise only.
Advanced Response Caching Options
Note
This feature is only available in NCache 5.2 onwards.
Database Dependency
NCache lets you add Database Dependency to the cached response 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 in sync with the data in the database.
Data Invalidation
Another technique provided by NCache to keep the cache data fresh and get rid of stale data is Data Invalidation. 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 data. For example, on successfully removing an item from your shopping cart on 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 the data invalidation tag set to 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 the following NuGet package in your application based on your NCache version:
- Enterprise: AspNetCore.ResponseCache.NCache
- To utilize NCache's methods for Response Caching, include the following namespace to your application:
- The cache must be running.
- The application must be connected to cache before performing the operation.
- For API details, refer to: AddNCacheResponseCachingServices, NCacheConfiguration.
- 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 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 a connection with the server for adding the Database Dependency. In the 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": "demoCache",
"EnableLogs": "True",
"ExceptionsEnabled": "True"
"DefaultConnectionStringName": "DBServer1"
},
"ConnectionStrings": {
"DBServer1": "Data Source=20.20.20.40 \\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:The
AddOptions.Configure<NCacheConfiguration>
extension method gets called at runtime. You can use this method to add services to the container.The
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 that is in the cache as a unique identifier.<depends-on>
: A query that 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 with 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 is used.
<dependency type: "SQLServer" connection-string-name="DBServer">
<invalidates>
: A boolean flag that is set to 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 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 NCache Management Center/NCache Monitor for NCache Enterprise, or PerfMon Counters for NCache 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.