如果应用程序保持空闲,如何使会话超时

How can I make the session timeout if the application keep idle

我想在 layout.cshtml 页面中添加会话超时功能。会话超时后,我必须显示 TimeOut div 以显示消息并再次重新登录。如何从函数 SessionLogOut()

调用超时 div

下面给出了 layout.cshtml 代码。

<head>

</head>    

<body onload="return disableBack()" ondragstart="return false;" ondrop="return false;">
    @if (HttpContextAccessor.HttpContext.Session.GetString("UserName") == null)
    {
        <div id="TimeOut" class=" text-center">Your session has expired, please<a href="/Home/Index" class="btn signout " style="padding: 1px 5px 1px 5px;">click here to login</a>again</div>
        <div class="main-content hidden">
            @RenderBody()
        </div>
    }
    else
    {
    }
<script type="text/javascript">
{
  $(document).ready(function () {

              SessionLogOut();
         });
 function SessionLogOut()
{
}
}

如果您想使用 js 显示 div,这里有一个工作演示:

@using Microsoft.AspNetCore.Http;
@inject IHttpContextAccessor HttpContextAccessor

<div id="session">
</div>

<script>
    $(document).ready(function () {
        var session = '@HttpContextAccessor.HttpContext.Session.GetString("UserName")';
        if (session == "") {
            SessionLogOut();
        }
    });
    function SessionLogOut() {
        $("div#session").append("<div id=\"TimeOut\" class=\"text-center\">Your session has expired, please<a href=\"/Home/Index\" class=\"btn signout\" style=\"padding: 1px 5px 1px 5px;\">click here to login</a>again</div>");

    }
</script>

因为您的标题是 How can I make the session timeout if the application keep idle。确保您已设置 session 超时,如下所示:

services.AddSession(options =>
{
      options.IdleTimeout = TimeSpan.FromSeconds(5);
});

调用你设置的方法session,然后调用其他方法,保持ide超过五秒后,刷新页面,超时div会显示。

结果:

整个Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        // This lambda determines whether user consent for non-essential cookies is needed for a given request.
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });
    services.AddHttpContextAccessor();
    services.AddSession(options =>
    {
        options.IdleTimeout = TimeSpan.FromSeconds(5);
    });
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseSession();

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseCookiePolicy();
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}