This may be an extremely unnecessary implementation, but please bear with me.
Startup.cs
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(Configuration.GetValue<double>("Custom:SessionTimeout"));
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
appsettings.json
{
...,
"Custom": {
"CookieTimeout": 15,
"LockTimeout": 15,
"SessionTimeout": 15
}
}
My intention is to allow the ability to modify the value for session timeout. As provided above, the Session's IdleTimeout in Startup.cs uses a value defined in the appsettings.json. For testing, I published the application to IIS, I restarted the server. The default value was set to 15 (minutes). It worked properly. However, afterwards, regardless of any value changed, it will still use the default value (15), unless the server was restarted.
My question is, is it possible to have the changes immediately take effect without performing a restart on the server?
First the IOptions<SessionOptions>
is consumed once by the singleton middleware of SessionMiddleware
. That options is singleton as well. So you just need to obtain that options and update the values.
However the point here is when to update it? As you want looks like it's when you save the configuration file. Asp.net core supports a feature to monitor the file changes. The change will be notified via an IChangeToken
(which can be used only once for each obtained token). After handling the change, you need to obtain another change token to observe the change. However you don't have to do that logic manually because we have the static method ChangeToken.OnChange
which can be conveniently to configure the change handler. It accepts a factory to get IChangeToken
and a handler (to be called after some change occurs). The IConfiguration
exposes a method called GetReloadToken
to get an IChangeToken
so we can use that.
Here's the code:
//inside Startup.ConfigureServices
services.AddSession(options => {
options.IdleTimeout = TimeSpan.FromMinutes(Configuration.GetValue<double>("Custom:SessionTimeout"));
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
//update options on changes made to the configuration file
ChangeToken.OnChange(
() => Configuration.GetReloadToken(),
so => {
so.IdleTimeout = TimeSpan.FromMinutes(Configuration.GetValue<double>("Custom:SessionTimeout"));
}, options);
});