Use for ASP.NET Core Sessions in Professional
NuGet is a popular way of simplifying the use of NCache in your .NET Core application. When NCache package is installed using NuGet, it copies the library files to your Visual Studio solution and automatically updates your project (add references, change config files, etc.).
Step 1:
Create a new ASP.NET Core Web application in Microsoft Visual Studio.
Step 2:
Use the following command in Package Manager Console inside Visual Studio to install NCache NuGet package:
Install-Package AspNetCore.Session.NCache.Professional
Once this package is installed, verify that references of the following assemblies have been added to your application.
- Alachisoft.NCache.SessionStoreProvider.dll
- Alachisoft.NCache.CoreSessionStoreProvider.dll
Step 3:
Include the following namespace in Startup.cs
of your application to utilize the APIs provided by NCache.
using Alachisoft.NCache.Web.SessionState;
Step 4:
Also, make sure that the following section has been added to the AppSettings.json of your ASP.NET Core application.
{
"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]
Please note that
idletimeout="5"
here means that your sessions will expire after 5 minutes of inactivity. You can change this value according to your need.
After following the above mentioned steps to configure NCache for sessions, all ASP.NET Core sessions of this application are stored in demoClusteredCache, provided that the cache is configured and running. You can modify the following attributes according to your needs.
CacheName: This is name of the cache you have created.
EnableLogs ("true"/"false"): This turns on or off error logging. If EnableLogs is turned on, then all errors are logged in /opt/ncache/log-files/SessionStoreProvider.
SessionAppId: If you have multiple applications or app domains running on the same web farm and are accessible from the same application, then you you can choose whether or not to share your sessions across app domains. If you aren't interested in sharing sessions across app domains, then assign a unique sessionAppId for each app domain. This ensures that each app domain places its own sessionAppId to the SessionId, thus making it impossible for the other app domains that might be using the same SessionId to fetch the same session.
Step 5:
NCache offers the AddNCacheSession()
method which allows you to initialize configurations from external files before adding the session services to the container. Through this method, you can refer to the configurations by providing the name of the section containing JSON format configurations in Appsettings.json. In the ConfigureServices()
method of Startup.cs, add the name of the JSON format section as follows:
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 successfully, HTTP request pipeline can now be configured. You can do so by adding a middleware in the Configure()
method. The following code shows the addition of a middleware layer through UseNCacheSession()
extension method in IApplicationBuilder
.
Note
The NCache session middleware layer should always be 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 9:
Make sure that all objects in session are serializable:
If you are using the InProc mode of ASP.NET Core Sessions, then the objects do not need to be marked Serializable. However, if you are using either StateServer or SqlServer modes for Sessions, then your objects are already serializable.
In either case, before using NCache for your sessions, you must ensure that all the custom objects that you’re putting in the Session are marked serializable. Add a
[Serializable]
tag before all your class definitions.
See Also
Create a Cache
Simulate Cache Usage
Use NCache from .NET Application
NCache Programmer's Guide