繁体   English   中英

使用 ASP.net 核心 C# 在 MVC 应用程序中 session 过期或空闲时间后重定向到登录页面

[英]Redirect to Login page after session expire or idle time in MVC application using ASP.net core C#

我正在使用 ASP.NET 核心。 当 session 过期或用户空闲 10 分钟时,我想重定向到登录页面。 我怎样才能做到这一点? 目前,注销正在发生(当用户点击任何链接或提交按钮时,应用程序会重定向到登录页面。当用户点击按钮或链接时会发生这种情况。)我想重定向到登录页面而不需要用户点击按钮或关联。

目前我已经在 Startup.cs 中编写了这段代码

  1. ConfigureServices 内部

     services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(10); }); services.AddMvc(options => options.EnableEndpointRouting = false); services.ConfigureApplicationCookie(options => { options.ExpireTimeSpan = System.TimeSpan.FromMinutes(10); options.SlidingExpiration = true; options.LoginPath = "/MVCApp/Login"; });
  2. 在配置中

     app.UseSession(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); endpoints.MapRazorPages(); }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); });

对此有任何建议。

你应该像这样在客户端处理这个:

<script>
(function() {

    const idleDurationSecs = 60;    // X number of seconds
    const redirectUrl = '/logout';  // Redirect idle users to this URL
    let idleTimeout; // variable to hold the timeout, do not modify

    const resetIdleTimeout = function() {

        // Clears the existing timeout
        if(idleTimeout) clearTimeout(idleTimeout);

        // Set a new idle timeout to load the redirectUrl after idleDurationSecs
        idleTimeout = setTimeout(() => location.href = redirectUrl, idleDurationSecs * 1000);
    };

    // Init on page load
    resetIdleTimeout();

    // Reset the idle timeout on any of the events listed below
    ['click', 'touchstart', 'mousemove'].forEach(evt =>
        document.addEventListener(evt, resetIdleTimeout, false)
    );

 })();
</script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM