我无法在 ASP.NET Core 2.0 中增加 session 超时。 session 每 20 到 30 分钟就会过期。当我将时间减少到 1 分钟并进行调试时,它工作正常,但是当它增加到超过 30 分钟或数小时/天时,它不会持续到指定的持续时间。
session 在 Debug模式以及来自 IIS(发布后托管)下 30 分钟后过期。
options.IdleTimeout = TimeSpan.FromMinutes(180);
我在 startup.cs 文件中使用以下代码。public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Adds a default in-memory implementation of IDistributedCache.
services.AddDistributedMemoryCache();
services.ConfigureApplicationCookie(options =>
{
options.Cookie.HttpOnly = true;
options.Cookie.Expiration = TimeSpan.FromDays(3);
options.ExpireTimeSpan= TimeSpan.FromDays(3);
options.SlidingExpiration = true;
});
services.AddSession(options =>
{
// Set a short timeout for easy testing.
options.IdleTimeout = TimeSpan.FromMinutes(180);
});
services.AddSingleton<IConfiguration>(Configuration);
// In production, the Angular files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IConfigurationSettings configurationSettings)
{
//
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseSession();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseExceptionHandler(
builder =>
{
builder.Run(
async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.ContentType = "application/json";
var ex = context.Features.Get<IExceptionHandlerFeature>();
if (ex != null)
{
if(ex.Error is SessionTimeOutException)
{
context.Response.StatusCode = 333;
}
if (ex.Error is UnauthorizedAccessException)
{
context.Response.StatusCode =999;
}
var err = JsonConvert.SerializeObject(new Error()
{
Stacktrace = ex.Error.StackTrace,
Message = ex.Error.Message
});
await context.Response.Body.WriteAsync(Encoding.ASCII.GetBytes(err), 0, err.Length).ConfigureAwait(false);
}
});
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
// To learn more about options for serving an Angular SPA from ASP.NET Core,
// see https://go.microsoft.com/fwlink/?linkid=864501
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
}
最佳答案
问题可能会出现,因为您的应用程序池在 IIS 上被回收。默认情况下,IIS 应用程序池每 20 分钟后回收一次。
尝试增加应用程序池回收时间。
更改应用程序池回收时间。通过以下链接
https://www.coreblox.com/blog/2014/12/iis7-application-pool-recycling-and-idle-time-out
关于asp.net-core - 无法在 ASP.NET Core 2.0 中增加 session 超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50228068/