• Products
  • Solutions
  • Customers
  • Resources
  • Company
  • Pricing
  • Download
Try Playground
  • Client Side Features
  • ASP.NET Core Caching
  • Response Caching
  • Configure and Use
Show / Hide Table of Contents
  • Programmer's Guide
  • Setting Up Development Environment
    • .NET
      • Client API Prerequisites
      • Server-side API Prerequisites
    • Java
      • Client API Prerequisites
      • Server-side API Prerequisites
    • Python
      • Client API Prerequisites
    • Node.js
      • Client API Prerequisites
  • Client Side API Programming
    • Error Handling
    • Troubleshooting
    • Cache Keys and Data
    • How to Connect to Cache
    • Basic Operations - An Overview
      • Add Data
      • Update/Insert Data
      • Retrieve Data
      • Remove Data
    • Groups
      • Overview
      • Add/Update Data with Groups
      • Retrieve Data with Groups
      • Remove Data with Group
      • Search Group Data Using SQL
      • Delete Group Data Using SQL
    • Tags
      • Overview
      • Add/Update Data with Tags
      • Retrieve Data with Tags
      • Remove Data with Tags
      • Search Tag Data Using SQL
      • Delete Tag Data Using SQL
    • Named Tags
      • Overview
      • Add/Update Data with Named Tags
      • Remove Data with Named Tags
      • Search Data with Named Tags Using SQL
      • Delete Data with Named Tags Using SQL
    • Expirations
      • Overview
      • Absolute Expiration
      • Sliding Expiration
    • Data Dependency
      • Key Dependency
      • Multi-Cache Dependency
    • Dependency on Database
      • SQL Server
      • Oracle
      • OleDB with Polling
      • CLR Procedures in SQL Server
    • Dependency on External Source
      • File Dependency
      • Custom Dependency
      • Aggregate Dependency
    • Locks
      • Types of Locking
      • Pessimistic Locking
      • Optimistic Locking
    • SQL Query
      • Overview
      • Define Indexes Programmatically
      • Query with ExecuteReader and ExecuteScalar
      • Delete Data with ExecuteNonQuery
      • SQL Reference
    • LINQ Query
      • Overview
      • LINQ Query for Objects
      • LINQ Reference
    • Data Structures
      • Overview
      • List
      • Queue
      • Set
      • Dictionary
      • Counter
      • Invalidation Attributes
      • Searchable Attributes
      • Query on Data Structures
      • Remove from Data Structure
    • Events
      • Cache Level Events
      • Item Level Events
      • Management Level Events
    • Pub/Sub Messaging
      • Overview
      • Topics
      • Publish Messages
      • Subscribe to a Topic
      • Pub/Sub Events
    • Continuous Query
      • Overview
      • Use Continuous Query
    • Stream Processing
      • Add/Update Stream Data
      • Retrieve Stream Data
    • JSON
      • Overview
      • Use JSON Objects
      • Query JSON Data
    • Security API
      • Login with Credentials
    • Management API
    • Clear Cache
    • Error Logging
    • Location Affinity
  • Server-side API Programming
    • Loader and Refresher
      • Overview
      • Implement Loader and Refresher
      • Components of Loader/Refresher
    • Data Source Providers
      • Read-through
        • Implement Read-through
        • Use Read-through
      • Write-through
        • Implement Write-through
        • Use Write-through
        • Use Write-behind
    • Custom Dependency
      • Implement Extensible Dependency
      • Implement Bulk Extensible Dependency
      • Implement Notify Extensible Dependency
    • Bridge Conflict Resolver
    • Entry Processor
      • Overview
      • Implement Entry Processor
    • MapReduce
      • Overview
      • Implement MapReduce
      • Use MapReduce
    • MapReduce Aggregator
      • Overview
      • Implement and Use Aggregator
    • Compact Serialization
  • Client Side Features
    • ASP.NET Core Caching
      • Session Storage
        • Session Provider
        • IDistributedCache
        • Sessions Usage
        • Multi-site Session Provider
        • Session Sharing with ASP.NET
      • SignalR
        • NCache Extension for SignalR Core
      • Response Caching
        • Configure and Use
        • Configure with IDistributedCache
      • Data Caching
        • NCache API
        • IDistributedCache API
      • Data Protection Provider
        • Configure
    • Java Web App Caching
      • Web Sessions
        • Overview
        • Configure App
          • Add Maven Dependencies
          • Deploy Application
        • Multi-site Sessions
    • Node.js App Caching
      • Web Sessions
    • ASP.NET Caching Benefits and Overview
      • ASP.NET Session State Provider Properties
      • Multi-region ASP.NET Session State Provider Configuration
      • Session Sharing between ASP.NET and ASP.NET Core
      • ASP.NET SignalR Backplane
        • NCache Extension for SignalR
      • ASP.NET View State Caching
        • View State Content Optimization Configuration
        • Group View State with Sessions
        • Limit View State Caching
        • Page Level Grouping
      • ASP.NET Output Cache
        • Output Caching Provider Overview
        • Output Cache with Custom Hooks
  • .NET Third Party Integrations
    • Entity Framework (EF) Core
      • Installation
      • Configure
      • EF Core Extension Methods
        • Extension Methods
        • Cache Handle
        • Caching Options
        • Query Deferred API
      • Logging in EF Core
    • Entity Framework EF 6
      • EF Second Level Cache
      • EF Caching Resync Provider
      • EF Caching Configuration File
    • NHibernate
      • Second Level Cache
      • Query Caching
      • Synchronize Database with Cache
    • Debug NCache Providers in Visual Studio
  • Java Third Party Integrations
    • Hibernate
      • Second Level Cache
      • Configure Cacheable Objects and Regions
      • Configure Application
      • Query Caching
    • Spring
      • Overview
      • Use NCache with Spring
        • Configure Generic Provider
        • Configure JCache Spring Caching Provider
        • Configure Caching Declaration
        • Configure Spring Sessions
    • JCache API
      • CRUD Operations
      • Expiration
      • Events
  • Third-Party Wrappers
    • AppFabric to NCache Migration
      • AppFabric API vs. NCache API
      • Configuration Differences Between AppFabric and NCache
      • Migrating from an AppFabric Application to NCache
    • Redis to NCache Migration
      • Redis to NCache Migration
    • Memcached Wrapper
      • Memcached Gateway Approach
      • Memcached Client Plugin for .NET

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.

  • .NET
  • Install the following NuGet package in your application based on your NCache edition:
    • Enterprise: AspNetCore.ResponseCache.NCache
  • To utilize NCache's methods for Response Caching, include the following namespace to your application:
    • Alachisoft.NCache.ResponseCaching;
  • 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 the 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.

In This Article
  • Advanced Response Caching Options
    • Database Dependency
    • Data Invalidation
  • Using NCache for Response Caching
    • Configure Response Caching Service
    • Configure NCache as a Distributed Cache
  • Add Distributed Cache NCache Tag Helper to View Class
  • Add Distributed Cache Tag Helper to View Class
  • Additional Resources
  • See Also

Contact Us

PHONE

+1 (214) 764-6933   (US)

+44 20 7993 8327   (UK)

 
EMAIL

sales@alachisoft.com

support@alachisoft.com

NCache
  • NCache Enterprise
  • NCache Professional
  • Edition Comparison
  • NCache Architecture
  • Benchmarks
Download
Pricing
Try Playground

Deployments
  • Cloud (SaaS & Software)
  • On-Premises
  • Kubernetes
  • Docker
Technical Use Cases
  • ASP.NET Sessions
  • ASP.NET Core Sessions
  • Pub/Sub Messaging
  • Real-Time ASP.NET SignalR
  • Internet of Things (IoT)
  • NoSQL Database
  • Stream Processing
  • Microservices
Resources
  • Magazine Articles
  • Third-Party Articles
  • Articles
  • Videos
  • Whitepapers
  • Shows
  • Talks
  • Blogs
  • Docs
Customer Case Studies
  • Testimonials
  • Customers
Support
  • Schedule a Demo
  • Forum (Google Groups)
  • Tips
Company
  • Leadership
  • Partners
  • News
  • Events
  • Careers
Contact Us

  • EnglishChinese (Simplified)FrenchGermanItalianJapaneseKoreanPortugueseSpanish

  • Contact Us
  •  
  • Sitemap
  •  
  • Terms of Use
  •  
  • Privacy Policy
© Copyright Alachisoft 2002 - 2025. All rights reserved. NCache is a registered trademark of Diyatech Corp.
Back to top