ASP.NET Core Session in NCache
Install NuGet Package
Install the NuGet package Alachisoft.NCacheSessionServices.Enterprise to your application by executing the following command in the Package Manager Console:
Install-Package Alachisoft.NCacheSessionServices.Enterprise
Include Namespaces
To utilize the APIs, include the following namespaces in your application in Startup.cs
:
Alachisoft.NCache.Web.SessionState
Microsoft.AspNetCore.Hosting
Using NCache Session Management Services with ASP.NET Core requires two steps:
- Configuring the session management service
- Adding middleware to the application
Step 1: Configure NCache Session Management Service
The session management service needs to be initialized. In Startup.cs, use
the SetNCacheSessionConfiguration()
extension method
on IServiceCollection
in ConfigureServices()
to initialize the service. The
very basic overload of this extension method takes
an IOptions<NCacheSessionConfiguration>
as its base configuration.
There are two methods to specify configurations:
- Through your application as
IOptions
or - In JSON format in Appsettings.json of your application.
Important
Refer to ASP.NET Core Session Provider in Programmers' Guide for detailed description of each configuration member.
Method 1: Specifying Configurations in IOptions
The session can be initialized by the AddNCacheSession()
extension method that
takes an IOptions<NCacheSessionConfiguration>
object as the configuration.
Note
The configuration must always contain the cache name.
public void ConfigureServices(IServiceCollection services)
{
//Add framework services
services.AddMvc();
//Add services to the container with configured session (SessionAppId = NcacheSessionApp) for cache "demoClusteredCache", with logging enabled and idle timeout set to 5
services.AddNCacheSession(configuration =>
{
configuration.CacheName = "demoClusteredCache";
configuration.EnableLogs = true;
configuration.SessionAppId = "NCacheSessionApp";
configuration.SessionOptions.IdleTimeout = 5;
configuration.SessionOptions.CookieName = "AspNetCore.Session";
});
}
Method 2: Specifying Configurations in Appsettings.json
The configurations for the services can also be provided in JSON format as a section in Appsettings.json of your ASP.NET application:
Note
The configuration must always contain the cache name.
{
"AppSettings": {
"SiteTitle": "ASP.NET MVC Music Store",
"CacheDbResults": true,
"CacheName": "demoClusteredCache"
},
"NCacheSessions": {
"SessionAppId": null,
"SessionOptions": {
"CookieName": "AspNetCore.Session",
"CookieDomain": null,
"CookiePath": "/",
"CookieHttpOnly": "True",
"IdleTimeout": "5",
"CookieSecure": "None"
},
"CacheName": "demoClusteredCache",
"EnableLogs": "True",
"RequestTimeout": "90"
},
"DefaultAdminUsername": "Administrator@test.com",
"DefaultAdminPassword": "myPassword",
"Data": {
"DefaultConnection": {
"ConnectionString": "Server=(localdb)\\MSSQLLocalDB;Database=MusicStore;Trusted_Connection=True;MultipleActiveResultSets=true;Connect Timeout=30;"
}
}
}
NCache provides the SetNCacheSessionConfiguration()
method to initialize
configurations from external files before adding the session services to the
container. Using this method, 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.SetNCacheSessionConfiguration(Configuration.GetSection("NCacheSettings"));
services.AddNCacheSession();
}
Step 2: Add Middleware to Application
Once the services have been initialized, you can now configure the HTTP request
pipeline by adding middleware in the Configure()
method. The following is an
excerpt showing the addition of a middleware layer through the use
of UseNCacheSession()
extension method inIApplicationBuilder
. The NCache
session middleware 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?}");
});
}