NCache for .NET Web API: The Key to Building High-Performance Applications
NCache is a powerful distributed caching solution designed to optimize .NET Web API performance. By reducing database bottlenecks…
NCache for .NET Web API: The Key to Building High-Performance Applications
NCache is a powerful distributed caching solution designed to optimize .NET Web API performance. By reducing database bottlenecks, enhancing scalability, and ensuring high availability, NCache significantly improves response times for high-traffic applications. This article explores how NCache empowers developers to build high-performance, scalable, and reliable .NET Web API applications effortlessly.

NCache for .NET Web API: The Key to Building High-Performance Applications
Now we try show how NCache work for distributed cache management with .NET web api / web application.
To create a full .NET Web API solution using NCache for distributed caching, follow the steps below. I’ll guide you through the entire process, from setting up the environment to implementing NCache in a .NET 7 Web API project.
Prerequisites:
- .NET SDK: Ensure you have .NET SDK installed (preferably .NET 6 or later).
- NCache: You can use the NCache Community Edition for development. Download it from the NCache website. *For Installation procedure (its only for licence and industrial purpose)* . better for dev & test Widows Desktop NCache. then install and try..
- IDE: Visual Studio or Visual Studio Code.
Steps 1: Create a New .NET 7 Web API Project
Open a terminal or command prompt. Create a new ASP.NET Core Web API project:
dotnet new webapi -n NCacheWebApi
cd NCacheWebApi
Step 2: Install NCache NuGet Packages
Install the NCache SDK for .NET:
dotnet add package Alachisoft.NCache.SDK --version 5.3.4
Optionally, you can also install the NCache Manager for easy management (GUI) if required. For Installation procedure NCache manager.
Step 3: Set Up NCache Configuration
Create a NCache Configuration and DTo
public class NCacheSettings
{
public string CacheName1 { get; set; }
public string ClusterIP1 { get; set; }
public int Port1 { get; set; }
public string CacheName2 { get; set; }
public string ClusterIP2 { get; set; }
public int Port2 { get; set; }
}
public class CacheItemDto
{
public string Key { get; set; }
public string Value { get; set; }
}
Configure NCache: Create a configuration file NCache.config in the root of your project or use the default one provided by NCache Manager. Ensure you define a cache with the necessary settings.
Here is an example of client.ncconf
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<ncache-server connection-retries="5" retry-connection-delay="0" retry-interval="1" client-request-timeout="90" connection-timeout="5" port="9800" />
<cache id="ClusteredCache" enable-client-logs="False" log-level="error">
<server name="192.168.1.4" port="9888" />
</cache>
<cache id="demoCache" enable-client-logs="False" log-level="error">
<server name="192.168.1.4" port="7801" />
</cache>
<cache id="myCache" enable-client-logs="False" log-level="error">
<server name="127.0.0.1" port="9800" />
</cache>
</configuration>
Step 4: Update the Program.cs File
In Program.cs, configure the NCache service:
using Alachisoft.NCache.Client;
using Alachisoft.NCache.Common;
using Alachisoft.NCache.Web.Caching;
using Microsoft.Extensions.Options;
using NCacheWebApi.Models;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Bind NCache configuration from appsettings.json
builder.Services.Configure<NCacheSettings>(builder.Configuration.GetSection("NCacheConfig"));
// Configure NCache client
// Create new CacheConnectionOptions instance
var options = new CacheConnectionOptions();
// Specify the cache connection options to be set
options.RetryInterval = TimeSpan.FromSeconds(5);
options.ConnectionRetries = 2;
options.EnableKeepAlive = true;
options.KeepAliveInterval = TimeSpan.FromSeconds(30);
// Enter the credentials
//string cacheName = "demoCache";
//string userId = "userid";
//string password = "mypassword";
//options.UserCredentials = new Credentials(userId, password)
builder.Services.AddSingleton<ICache>(serviceProvider =>
{
var settings = serviceProvider.GetRequiredService<IOptions<NCacheSettings>>().Value;
var cacheName1 = settings.CacheName1;
var clusterIP1 = settings.ClusterIP1;
var cacheName2 = settings.CacheName2;
var clusterIP2 = settings.ClusterIP2;
// Connect to NCache cluster
// Connect to the caches
ICache cache1 = CacheManager.GetCache(cacheName1, options);
ICache cache2 = CacheManager.GetCache(cacheName2, options);
//ICache cache3 = CacheManager.GetCache("myCache", options);
return cache1;
});
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Step 5: Create a Sample Controller
Create a new controller WeatherForecastController.cs:
using Alachisoft.NCache.Client;
using Alachisoft.NCache.Runtime.Caching;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NCacheWebApi.Models;
namespace NCacheWebApi.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class CacheController : ControllerBase
{
private readonly ICache _cache;
public CacheController(ICache cache)
{
_cache = cache;
}
[HttpGet("get/{key}")]
public IActionResult GetValue(string key)
{
//var readThruOptions = new ReadThruOptions(); // Set your options if needed
var value = _cache.Get<string>(key) ;
if (value == null)
{
return NotFound();
}
return Ok(value);
}
[HttpPost("set")]
public IActionResult SetValue([FromBody] CacheItemDto item)
{
_cache.Insert(item.Key, item.Value);
return Ok();
}
}
}
Step 6: Additional Configuration
Configure Caching Options: In appsettings.json, you can set additional NCache configuration options:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"NCacheConfig": {
"CacheName1": "ClusteredCache",
"ClusterIP1": "192.168.1.4", // NCache cluster IP
"Port1": 9888,
"CacheName2": "demoCache",
"ClusterIP2": "192.168.1.4", // NCache cluster IP
"Port2": 7801
},
"AllowedHosts": "*"
}
Handle Caching Exceptions: Implement error handling in your controller to manage scenarios when the cache is unavailable.
Step 7 : Run the Application
Start the NCache server if it’s not running. In the terminal, run the Web API project:
dotnet run

Test Save Data in Cache :

Data Retrive :

Step 8: Test Caching
- Make the initial request to the endpoint; you should see the freshly generated forecast data.
- Make the request again within the next minute; this time, you should receive the cached data.
Requset:
curl -X 'GET' \
'https://localhost:7033/api/Cache/get/test' \
-H 'accept: */*'
Response:
In the ever-evolving landscape of web development, performance and scalability are very important. That’s where distributed caching comes into play, and NCache stands out as a robust solution.
Request:
Curl
curl -X 'POST' \
'https://localhost:7033/api/Cache/set' \
-H 'accept: */*' \
-H 'Content-Type: application/json' \
-d '{
"key": "test1",
"value": "In the ever-evolving landscape of web development, performance and scalability are very important. That’s where distributed caching comes into play, and NCache stands out as a robust solution."
}'
Response:
200 success
Conclusion:
- Explore Advanced Features: Consider implementing cache expiration, cache dependencies, and notifications.
- Monitoring: Use NCache monitoring tools to keep track of cache performance and hit rates.
- Deployment: When ready, deploy your application along with NCache to a suitable environment, ensuring the cache is configured correctly for production.
Download Full Project NCache-for-.NET-Web-API
By following these steps, you can successfully implement caching in your .NET Web API applications using NCache. Let me know if you need any further assistance!
If you enjoy my content or find my work helpful, consider supporting me — your contribution helps fuel more projects and knowledge sharing! Buy Me a Coffee
I offered you others medium article: Visit My Profile
also, My GitHub: Md Hasan Monsur
Connect with me at LinkedIn : Md Hasan Monsur
메타데이터
- post_id
- 604faebfaa9f
- slug
- ncache-for-net-web-api-the-key-to-building-high-performance-applications-604faebfaa9f
- url
- https://medium.com/asp-dotnet/ncache-for-net-web-api-the-key-to-building-high-performance-applications-604faebfaa9f
- canonical_url
- https://medium.com/asp-dotnet/ncache-for-net-web-api-the-key-to-building-high-performance-applications-604faebfaa9f
- author_url
- https://medium.com/@hasanmcse
- status
- ok
- fetched_at
- 2026-07-22 11:47:57