NCache as Output Cache Provider
The NCache Output Cache integration provides a distributed backing store for ASP.NET Core Output Cache through the IOutputCacheStore interface. It allows ASP.NET Core applications to store complete HTTP responses in NCache so that cached responses can be shared across multiple application instances in a load-balanced environment.
NCache Output Cache integration can be configured using the following approaches:
- Using appsettings.json (Recommended for Production)
- Using an action delegate in Program.cs
Both approaches are supported through AddNCacheOutputCacheProvider overloads.
Important
For the NCache OpenSource edition, Output Cache is supported in NCache OSS 5.3.6.2 and later.
Note
Database-driven cache dependencies and cache security are not supported in the NCache OpenSource edition.
Note
Sliding expiration is currently not supported. The provider uses absolute expiration based on the Output Cache policy duration.
Prerequisites
Before configuring ASP.NET Core Output Cache with NCache, ensure that the following prerequisites are fulfilled:
- To configure ASP.NET Core Output Cache with NCache, install the following NuGet package in your .NET application:
- Enterprise: NCache.AspNetCore.OutputCaching
- OpenSource: NCache.OSS.AspNetCore.OutputCaching
- To utilize the Output Cache provider, include the following namespace in your application in Program.cs:
- Enterprise:
Alachisoft.NCache.OutputCaching - OpenSource:
NCache.OSS.AspNetCore.OutputCaching
- Enterprise:
- The cache must be running.
Method 1: Using appsettings.json
This approach defines the provider settings in appsettings.json and binds them through IConfiguration during application startup. It is recommended for production because connection settings can be changed between deployments without modifying or recompiling the application.
Step 1: Configure NCache Settings
The following configuration defines the NCache cache name, logging settings, and server connectivity information used by the Output Cache provider. Add the following configuration section in your appsettings.json file.
{
"NCache": {
"CacheName": "demoCache",
"EnabledLogs": false,
"EnableDetailLogs": false,
"ServerList": [
{
"Ip": "20.200.20.11",
"Port": 9800
}
]
}
}
Step 2: Register the Configuration Section
After defining the NCache settings in appsettings.json, register Output Cache, bind the NCache provider to the NCache configuration section, and enable Output Cache in the request pipeline. The endpoint uses CacheOutput() so its response can be stored and served from NCache.
Add the following code in your Program.cs file.
var builder = WebApplication.CreateBuilder(args);
// Configure Output Cache policies
builder.Services.AddOutputCache(options =>
{
options.AddBasePolicy(policy =>
policy.Expire(TimeSpan.FromSeconds(30)));
});
// Register NCache Output Cache provider using IConfiguration binding
builder.Services.AddNCacheOutputCacheProvider(
builder.Configuration.GetSection("NCache"));
var app = builder.Build();
// Enable Output Cache middleware
app.UseOutputCache();
// Configure a cacheable endpoint
app.MapGet("/", () => "Cached response")
.CacheOutput();
app.Run();
Method 2: Using an Action Delegate in Program.cs
In this approach, the Output Cache provider configuration is defined directly inside Program.cs through an action delegate passed to AddNCacheOutputCacheProvider. The action delegate allows cache connection settings, logging behavior, and server connectivity to be configured programmatically during application initialization.
The following configuration registers ASP.NET Core Output Cache middleware, configures NCache as the distributed Output Cache provider, enables Output Cache in the request pipeline, and applies Output Cache to an endpoint using CacheOutput().
Add the following code in your Program.cs file.
var builder = WebApplication.CreateBuilder(args);
// Configure Output Cache policies
builder.Services.AddOutputCache(options =>
{
options.AddBasePolicy(policy =>
policy.Expire(TimeSpan.FromSeconds(30)));
});
// Register NCache as the distributed Output Cache provider
builder.Services.AddNCacheOutputCacheProvider(options =>
{
options.CacheName = "demoCache";
options.EnabledLogs = false;
options.EnableDetailLogs = false;
// Configure NCache server connectivity
options.ServerList = new List<NCacheOutputCacheOptions.ServerConfig>
{
new NCacheOutputCacheOptions.ServerConfig
{
Ip = "20.200.20.11",
Port = 9800
}
};
});
var app = builder.Build();
// Enable Output Cache middleware
app.UseOutputCache();
// Configure a cacheable endpoint
app.MapGet("/", () => "Cached response")
.CacheOutput();
app.Run();
Configure Multiple Output Cache Policies
ASP.NET Core Output Cache allows multiple cache policies to be configured with different expiration settings. These policies can then be applied to specific endpoints based on application requirements.
The following example updates the existing AddOutputCache configuration to define two cache policies with different expiration durations.
// Configure multiple Output Cache policies with different expiration durations
builder.Services.AddOutputCache(options =>
{
// Define a short-duration cache policy (10 seconds)
options.AddPolicy("short", policy =>
policy.Expire(TimeSpan.FromSeconds(10)));
// Define a long-duration cache policy (5 minutes)
options.AddPolicy("long", policy =>
policy.Expire(TimeSpan.FromMinutes(5)));
});
builder.Services.AddNCacheOutputCacheProvider(
builder.Configuration.GetSection("NCache"));
var app = builder.Build();
app.UseOutputCache();
app.MapGet("/fast", () => "Fast response")
.CacheOutput("short");
app.MapGet("/slow", () => "Slow response")
.CacheOutput("long");
app.Run();
Configure Database Cache Dependencies
Database cache dependencies associate cached responses with database data. When a relevant change is detected in the monitored data, NCache removes the associated cached response. The next request then generates and caches an updated response. The Output Cache provider supports the following database dependencies:
SQL Server Cache Dependency: Uses SQL Server query notifications to monitor the data represented by a specified query. Use
SqlCacheDependencyto associate an Output Cache policy with the query and its database connection. When defining the dependency query:- Use fully qualified table names, such as
dbo.Products. - Specify the required columns explicitly.
- Do not use wildcard column selection, such as
SELECT *. - Provide the SQL Server connection string used to establish the dependency. If a connection string is not provided, the provider falls back to its default connection parameters.
- Use fully qualified table names, such as
Oracle Cache Dependency: Uses Oracle Database Change Notification (DCN) to monitor the data represented by a specified Oracle query. Use
OracleCacheDependencyto associate an Output Cache policy with the query and its database connection string. Ensure that the query is valid for the target Oracle database instance.
The following example defines named SQL Server and Oracle dependency policies. Each policy is applied to the endpoint whose cached response depends on the corresponding database data.
Note
The example demonstrates both supported dependency types. Configure only the dependency policies required by your application. For this example, define the SqlConnString and OracleConnString entries under ConnectionStrings in appsettings.json.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOutputCache(options =>
{
// Configure a SQL Server cache dependency policy
options.AddPolicy("SqlDependencyPolicy", policy =>
policy.SqlCacheDependency(
cmdText: "SELECT ProductID, ProductName FROM dbo.Products",
connectionString:
builder.Configuration.GetConnectionString("SqlConnString")
));
// Configure an Oracle cache dependency policy
options.AddPolicy("OracleDependencyPolicy", policy =>
policy.OracleCacheDependency(
cmdText: "SELECT ProductID, ProductName FROM Products",
connectionString:
builder.Configuration.GetConnectionString("OracleConnString")
));
});
builder.Services.AddNCacheOutputCacheProvider(
builder.Configuration.GetSection("NCache"));
var app = builder.Build();
app.UseOutputCache();
app.MapGet("/sqldata", () => "SQL-dependent data")
.CacheOutput("SqlDependencyPolicy");
app.MapGet("/oracledata", () => "Oracle-dependent data")
.CacheOutput("OracleDependencyPolicy");
app.Run();
In the above example, the /sqldata endpoint uses SqlDependencyPolicy, while the /oracledata endpoint uses OracleDependencyPolicy. When either endpoint is requested for the first time, its response is stored in NCache with the corresponding database dependency. If NCache detects a relevant change in the monitored SQL Server or Oracle data, it removes that cached response, and the next request generates and caches a fresh response.
Configure Cache Security
When security is enabled on NCache, the Output Cache provider can connect by using either user credentials or Group Managed Service Account (gMSA) authentication. Before configuring the provider, configure NCache security and authorize the required user or group for credential-based authentication as explained in Configure Security for Cache Server Nodes, or configure and authorize the gMSA account as explained in Configure Group Managed Service Account. You should configure only one authentication method for the provider connection.
Configure User Credentials
For credential-based authentication, provide values for both UserName and Password when registering the provider through an action delegate:
builder.Services.AddNCacheOutputCacheProvider(options =>
{
options.CacheName = "demoCache";
options.ServerList = new List<NCacheOutputCacheOptions.ServerConfig>
{
new NCacheOutputCacheOptions.ServerConfig
{
Ip = "20.200.20.11",
Port = 9800
}
};
options.UserName = "cacheUser";
options.Password = "cachePassword";
});
The same settings can be defined in appsettings.json as follows:
{
"NCache": {
"CacheName": "demoCache",
"ServerList": [
{
"Ip": "20.200.20.11",
"Port": 9800
}
],
"UserName": "cacheUser",
"Password": "cachePassword",
"UseGMSA": false
}
}
Warning
Credential-based authentication requires both UserName and Password. If only one is configured while UseGMSA is false, the provider does not apply security settings to the cache connection.
Configure gMSA Authentication
To use gMSA authentication, enable UseGMSA and leave UserName and Password unspecified:
builder.Services.AddNCacheOutputCacheProvider(options =>
{
options.CacheName = "demoCache";
options.ServerList = new List<NCacheOutputCacheOptions.ServerConfig>
{
new NCacheOutputCacheOptions.ServerConfig
{
Ip = "20.200.20.11",
Port = 9800
}
};
options.UseGMSA = true;
});
The equivalent appsettings.json configuration is as follows:
{
"NCache": {
"CacheName": "demoCache",
"ServerList": [
{
"Ip": "20.200.20.11",
"Port": 9800
}
],
"UseGMSA": true
}
}
Warning
Keep the two authentication methods mutually exclusive. If UserName and Password are provided together with UseGMSA, credential-based authentication takes precedence, and gMSA is ignored without an error or warning.
The provider determines the authentication method in the following order:
- When both
UserNameandPasswordare provided, credential-based authentication is used. - Otherwise, when
UseGMSAistrue, gMSA authentication is used. - If neither method is configured, no security settings are applied to the cache connection.
Configuration Properties
The following configuration properties are available in the NCacheOutputCacheOptions class.
Note
Properties marked with an asterisk (*) are required. All other properties are optional.
| Property | Description |
|---|---|
| CacheName* | Specifies the name of the NCache cache instance. The cache must already exist in the NCache cluster and is required for provider initialization. |
| ServerList | Specifies the list of NCache server nodes used for cache connectivity. Each ServerConfig entry contains an IP address and port number. IP addresses must be valid IPv4 or IPv6 addresses, and port values must be between 1–65535. The default port is 9800. |
| EnabledLogs | Enables NCache internal logging. When enabled, initialization and runtime errors are logged through the internal NCache logger. The default value is false. |
| EnableDetailLogs | Controls internal logging verbosity. When enabled, verbose logs are generated. Otherwise, informational logs are generated. The default value is false. |
| UserName (Enterprise Only) | Specifies the user name for credential-based authentication. It must be configured together with Password. |
| Password (Enterprise Only) | Specifies the password for credential-based authentication. It must be configured together with UserName. |
| UseGMSA (Enterprise Only) | Enables gMSA-based authentication. The default value is false. Leave UserName and Password unset when using gMSA. |