• Products
  • Solutions
  • Customers
  • Resources
  • Company
  • Pricing
  • Download
Try Playground
  • Client Side Features
  • ASP.NET Core Caching
  • Response Caching
  • Configure with IDistributedCache
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

Configure IDistributedCache for Response Caching

ASP.NET Core provides IDistributedCache for 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?

IDistributedCache for 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 IDistributedCache for Response Caching, NCache provides its own extension methods to configure services and middleware.

Prerequisites

  • .NET
  • Install the following NuGet packages in your application based on your NCache edition:
    • 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:
    • Alachisoft.NCache.Caching.Distributed;
  • 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 IDistributedCache 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 of IDistributedCache.

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 IDistributedCache for Response Caching on GitHub.

See Also

.NET: Alachisoft.NCache.ResponseCaching namespace.

In This Article
  • When to use Response Caching with IDistributedCache?
  • Response Caching Options
  • Using NCache for Response Caching
  • Prerequisites
    • Configure Response Caching Service
    • Configure NCache as a Distributed Cache
  • 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