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

Aju*_*jus 5 c# asp.net asp.net-mvc asp.net-core

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

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

  1. 内部配置服务

         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";
         });
    
    Run Code Online (Sandbox Code Playgroud)
  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?}");
         });
    
    Run Code Online (Sandbox Code Playgroud)

对此有何建议。

jac*_*ack 6

你应该在客户端处理这个问题,如下所示:

<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>
Run Code Online (Sandbox Code Playgroud)