Key Takeaways
- Caching is a technique for improving web application performance by temporarily storing requested data in memory for later reuse.
- Response caching refers to specifying cache-related headers on HTTP responses made by ASP.NET Core MVC actions.
- NCache is a cross-platform, open-source distributed caching framework from Alachisoft, built entirely using .NET.
- This article presents a discussion on how we can work with NCache and response caching middleware in ASP.NET Core.
NCache is a cross-platform, open-source distributed caching framework from Alachisoft. It is an extremely fast distributed caching framework that is linearly scalable. This article presents a discussion on how we can work with NCache and response caching middleware in ASP.NET Core.
Pre-requisites
You should have Visual Studio and ASP.NET Core installed in your system to work with the code examples discussed in this article. As of this writing, ASP.NET Core 3.0 has been released. You can download ASP.NET Core from here.
You can download Visual Studio 2019 from here.
What is caching and why is it needed?
Caching is a technique of storing the page output or application data across HTTP requests in the memory so that subsequent requests to the same piece of data or the page would be fetched from the memory. It improves application performance by faster page rendering and reduced consumption of the server’s resources. You can take advantage of caching for building applications that can scale and are high performant.
What is response caching and when should I use it?
Response caching enables you to cache the server responses of a request so that the subsequent requests can be served from the cache. It is a type of caching in which you would typically specify cache-related headers in the HTTP responses to let the clients know to cache responses. You can take advantage of the cache control header to set browser caching policies in requests that originate from the clients as well as responses that come from the server. As an example, cache-control: max-age=90 implies that the server response is valid for a period of 90 seconds. Once this time period elapses, the web browser should request a new version of the data.
The key benefits of response caching include reduced latency and network traffic, improved responsiveness, and hence improved performance. Proper usage of response caching can lower bandwidth requirements and improve the application’s performance.
You can take advantage of response caching to cache items that are static and have minimal chance of being modified, such as CSS, JavaScript files, etc.
Why use NCache as a response caching middleware?
You might need to leverage distributed caching if your web application has a high traffic. NCache is one of the best response caching middlewares available. NCache provides the following benefits as a distributed cache:
- 100% .NET—NCache is built in .NET and in .NET Core. It is one of the rare distributed caches available that is built entirely using .NET.
- Fast and scalable—NCache provides linear scalability and is very fast since it uses an in-memory distributed cache. Distributed caching is a concept in which the cached data might span multiple nodes or servers but within the same network hence enabling the cache to be scaled easily. The ability to scale linearly makes NCache a great choice when you experience performance challenges in your ASP.NET Core application during peak loads.
- High availability—One of the great features of NCache is its support for peer clustering architecture. NCache is capable of caching ASP.NET Core web pages using response caching so that there is no data loss when the cache server is down.
NCache provides several features, such as support for virtualization and containerization, asynchronous operations, cache locking, searchable cache, cache elasticity, cache administration and management, etc. You can find more about its features here.
Creating a new ASP.NET Core MVC application
To create a new ASP.NET Core MVC web application in Visual Studio 2019, follow the steps outlined below:
- Open the Visual Studio 2019 IDE
- Select the option “Create a new project”
- Select the option “ASP.NET Core Web Application” to specify the project type
- Click on “Next”
- Specify the project name and the location where you would like the new project to be saved
- Optionally, you can click on the option “Place solution and project in the same directory” checkbox
- Click on “Create”
- In the “Create a new ASP.NET Core Web Application” dialog window, select “Web Application (Model-View-Controller)” as the project template
- Select ASP.NET Core 3.0 from the DropDownList to specify the version of ASP.NET Core to be used
- Uncheck the “No Authentication,” “Configure for HTTPS,” and “Enable Docker Support” checkboxes since we wouldn’t be using any of these here
- Lastly, click on “Create”
Installing the NuGet packages
To work with NCache, you should install the following package(s) to your project via the NuGet Package Manager.
Install-Package NCache.Microsoft.Extensions.Caching
Note that you should include the Alachisoft.NCache.Caching.Distributed assembly in your programs to be able to work with the types in the NCache library. The following statement shows how you can do this.
using Alachisoft.NCache.Caching.Distributed;
Response caching options in NCache
There are three ways in which you can implement response caching using NCache. These include the following:
- HTTP Based Caching—this is a type of response caching that caches the data at the web browser’s end. HTTP based caching can reduce the server hits since subsequent requests for a particular resource can be served from the cache.
- In-Memory Caching - this is another type of response caching strategy in which data is cached in the memory of the web server. Note that the data in the cache is cleared when the ASP.NET engine is restarted since this is an in-proc mode of caching. In-memory caching is fast since it resides within the address space of your application.
- Distributed Caching—this is yet another strategy used in response caching. A distributed cache is external to an application. In this strategy, the cache is distributed across several servers in a web farm. Any of the servers can respond to a request for data from the client. You can take advantage of NCache from Alachisoft to implement a distributed cache. If you are running your application in a load balanced multi-server environment, NCache can help you in distributed caching of the application’s data.
Add response caching services
You can take advantage of the AddResponseCaching() method in the Startup class’s ConfigureServices() method to configure response caching. Open the Startup.cs file and write the following code in the ConfigureServices method.
public void ConfigureServices(IServiceCollection services)
{
services.AddResponseCaching();
services.AddMvc();
}
Note that the response caching middleware is implicitly available in ASP.NET Core. The UseResponseCaching extension method is used to add the middleware to the request processing pipeline.
Lastly, call the UseResponseCaching() method to add the response caching middleware to the pipeline. Refer to the code snippet given below that shows how this can be achieved.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
//Other code
app.UseResponseCaching();
}
Configure the response cache middleware
Response caching is a great feature in ASP.NET Core and is a built-in functionality. You can take advantage of it to reduce the number of requests a client makes to a web server. NCache can also be used as a response caching middleware. Let’s explore how this can be achieved.
To use NCache as a response cache middleware, you need to do the following:
- Specify the NCache settings in the Appsettings.json file
- Invoke the AddResponseCaching and AddNCacheDistributedCache methods in the ConfigureServices method of the Startup class.
You can configure NCache as a distributed cache in two ways:
- By specifying cache configuration in AppSettings.json
- By specifying cache configuration in IOptions
Specify cache configuration in AppSettings.json file
The following code snippet illustrates how you can specify cache configuration settings in the AppSettings.json file—a section named NCacheSettings has been added.
{
"NCacheSettings": {
"CacheName": "SpecifytheCacheNameHere",
"EnableLogs": "True",
"RequestTimeout": "60"
}
}
The ASP.NET Core IDistributedCache interface has been implemented in the NCache library. This allows you to use NCache as a response cache middleware in ASP.NET Core.
To use NCache as a NCache as your response cache middleware, write the following code in the ConfigureServices() method.
public void ConfigureServices(IServiceCollection services)
{
services.AddResponseCaching();
services.AddNCacheDistributedCache
(Configuration.GetSection("NCacheSettings"));
services.AddMvc();
}
Specify cache configuration in IOptions
You can also specify the NCache configuration details as IOptions as well. Refer to the code snippet given below to learnhow this can be achieved.
public void ConfigureServices(IServiceCollection services)
{
//Write code to add other services
services.AddMvc();
services.AddNCacheDistributedCache(options =>
{
options.CacheName = "SpecifytheCacheNameHere";
options.EnableLogs = true;
options.ExceptionsEnabled = true;
});
}
In the section that follows, we’ll examine how we can use NCache as a response caching middleware in the action methods.
Use response caching in the action methods
Assuming that you’ve configured the response caching middleware successfully, you can use the following code to take advantage of response caching in the action method.
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[ResponseCache(Duration = 60, Location = ResponseCacheLocation.None, NoStore = false)]
public IActionResult GetData()
{
//Write your code here
}
}
The Duration parameter is used to specify how long the data will remain in the cache. The ResponseCacheAttribute is used to specify the parameters in response caching. You can take advantage of the Location parameter to indicate if any client or intermediate proxy will cache the data. The possible values of the Location parameter are: ResponseCacheLocation.None, ResponseCacheLocation.Any, and ResponseCacheLocation.Client. If the value is ResponseCacheLocation.Any, it implies that the client or a proxy will cache the data. If the value is ResponseCacheLocation.Client, it implies that the client will cache the data. The NoStore parameter can have boolean values and if set to true, the Cache-Control header is set to no-store.
Use Distributed Cache Tag Helper
Now that NCache has been configured for response caching, you can specify the content that you would like to cache. To achieve this, you can take advantage of Distributed Cache Tag Helpers in ASP.NET Core.
The following code snippet illustrates how you can specify an item to remain in the cache forever.
<distributed-cache name="Key:A" >
<div>@DateTime.Now.ToString()</div>
</distributed-cache>
If you would like to set an expiry for a cached item, here’s what you need to write.
<distributed-cache name="Key:B" expires-after ="TimeSpan.FromSeconds(30)">
<div>@DateTime.Now.ToString()</div><br />
</distributed-cache>
The following code snippet illustrates how you can specify an item that will only be removed from cache if the “vary-by” value is changed.
<distributed-cache name="Key:C" vary-by ="test">
<div>@DateTime.Now.ToString()</div><br />
</distributed-cache>
Testing
To test the code examples given in the earlier section, you can create a new ASP.NET Core MVC application and write the following code in the Index.cshtml file:
<distributed-cache name="Key:A" >
<div>@DateTime.Now.ToString()</div>
</distributed-cache>
<distributed-cache name="Key:B" expires-after ="TimeSpan.FromSeconds(30)">
<div>@DateTime.Now.ToString()</div><br />
</distributed-cache>
<distributed-cache name="Key:C" vary-by ="test">
<div>@DateTime.Now.ToString()</div><br />
</distributed-cache>
When you execute the application you’ll observe that three DateTime values are displayed in the web browser. While the first and the third one doesn’t change, the second one changes the value after every 30 seconds.
Summary
Caching is a proven technique used in web applications to improve the performance and responsiveness. Response caching is a caching technique in which the response is served from the cache. ASP.NET Core provides support for response caching using the response caching middleware. For more information on NCache and how it can be used in ASP.NET Core, you can refer to the online documentation for NCache.