Configure NCache for ASP.NET Core Sessions
You can simplify the use of NCache in your .NET Core application through NuGet packages. When NuGet is used to install the NCache package, it automatically copies the library files to your Visual Studio solution and updates your project for you (updates like add references, change config files, etc.).
Step 1:
Your first step should be to create a new ASP.NET Core application in Microsoft Visual Studio.
Step 2:
For NCache Open Source, you need to install the NCache NuGet Package available for Open Source. You can install this by executing the following command in the Package Manager Console of Visual Studio:
Install-Package AspNetCore.Session.NCache.OpenSource
Step 3:
Once the package has been installed, verify that the following Assembly References have been added to your application.
- Alachisoft.NCache.SessionStoreProvider.dll
- Alachisoft.NCache.SessionStateManagement.dll
- Alachisoft.NCache.CoreSessionStoreProvider.dll
Step 4:
Also, verify that the AppSettings.json of your ASP.NET Core application has the following section included in it.
{
"AppSettings": {
"SiteTitle": "ASP.NET MVC Music Store",
"CacheDbResults": true,
},
"NCacheSessions": {
"SessionAppId": "demoApp",
"SessionOptions": {
"CookieName": "AspNetCore.Session",
"CookieDomain": null,
"CookiePath": "/",
"CookieHttpOnly": "True",
"IdleTimeout": "5",
"CookieSecure": "None"
},
"CacheName": "demoClusteredCache",
"EnableLogs": "True",
"RequestTimeout": "90"
},
}
Note
Here, idletimeout="5"
means that your sessions will expire after 5 minutes of inactivity. You can control this number according to your application's requirement.
After this configuration, all ASP.NET Core sessions of this application will be stored in demoClusteredCache, as long as your cache is configured and running. You can change the following attributes according to your requirements.
CacheName: The name of the cache you’ve created.
EnableLogs: This enables or disables error logging. If it is turned on, then NCache logs all errors in %NCHOME%\log-files\SessionStoreProvider. The default values are true or false.
SessionAppId: If you have multiple app domains or applications running on the same web farm and are accessible from the same application, then you get to decide whether you want to share your sessions across app domains or not. If you don’t want to share sessions across app domains, then you can simply specify a unique sessionAppId for each app domain. This ensures that any other domain using the same SessionId does not fetch the same session.
Step 5:
NCache provides the AddNCacheSession method to initialize configurations from external files before the session services are added to the container. Using the method mentioned below, you can refer to the configurations by providing the name of the section containing JSON format configurations in Appsettings.json:
public void ConfigureServices(IServiceCollection services)
{
//Add framework services
services.AddMvc();
//Add services to the container
services.AddNCacheSession(Configuration.GetSection("NCacheSessions"));
}
Step 6:
Once the services have been initialized, the HTTP request pipeline can now be configured by adding middleware in the Configure
method. The following method shows how to add a middleware layer through the use of the UseNCacheSession
extension method in IApplicationBuilder
.
Note
Ensure that the NCache session middleware is stacked before the layer that utilizes the sessions.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseNCacheSession(); //store NCache session data
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=myApp}/{action=Index}/{id?}");
});
}
Step 7:
Ensure that all objects in session are serializable:
If you are using ASP.NET Core Sessions InProc mode, then the objects you are using do not need to be marked Serializable. However, if you are using StateServer or SqlServer modes for Sessions, then your objects are already serializable.
In either scenario, before using NCache for your sessions, you must ensure that all your custom objects going in Session are marked serializable. Simply add a
[Serializable]
tag before all your class definitions.
See Also
Create a Cache
Simulate Cache Usage
Monitor Caches in PerfMon
Use NCache from .NET Application
NCache Programmer's Guide