在 mvc 中处理会话超时

Handling session timeout in mvc

我正在尝试在 .net 核心应用程序中实现会话超时。重定向到登录页面在非 ajax request/full 回发中工作正常,但在 ajax 请求的情况下则不然。登录页面显示在 ajax 请求的 layout/current 页面中。

我写了一个中间件,它会首先调用控制器方法,其中重定向登录是written.Below是我的代码。

中间件

 app.Use(async (ctx, next) =>
            {
                if (ctx.GetTenantContext<AppTenant>() == null && !ctx.Request.Path.ToString().Contains("/Home/Redirect"))
                {
                    string redirect = "/Home/Redirect/";

                    if (ctx.Request.Path.ToString().Contains("Admin"))
                    {
                        redirect = "/Home/Redirect/Admin";
                    }
                    else
                    {
                        redirect = "/Home/Redirect/Trainee";
                    }


                    ctx.Response.Redirect(redirect, true);
                }
                else
                {
                    await next();
                }
            });

家庭控制器

[Route("/Home/Redirect/{AppType?}")]
        public async Task<IActionResult> Redirect()
        {
            string appType = string.Empty;
            string clientName = string.Empty;

            if (!string.IsNullOrEmpty(Convert.ToString(RouteData.Values["AppType"])))
            {
                appType = Convert.ToString(RouteData.Values["AppType"]);
            }

            await _signInManager.SignOutAsync();

            HttpContext.Session.Clear();

            if (!string.IsNullOrEmpty(appType))
            {
                if (appType == "Admin")
                {
                    if (HttpContext.Request.Cookies != null)
                    {
                        if (HttpContext.Request.Cookies["clientnamebe"] != null)
                        {
                            clientName = HttpContext.Request.Cookies["clientnamebe"].ToString();
                        }
                    }
                    return RedirectToRoute(new
                    {
                        controller = "Admin",
                        action = "Login",
                        clientname = clientName

                    });
                }
                else
                {
                    if (HttpContext.Request.Cookies != null)
                    {
                        if (HttpContext.Request.Cookies["clientnamefe"] != null)
                        {
                            clientName = HttpContext.Request.Cookies["clientnamefe"].ToString();
                        }
                    }
                    return RedirectToRoute(new
                    {
                        controller = "Account",
                        action = "Login",
                        clientname = clientName

                    });
                }
            }

            return View();
        }

登录方法中,我只是返回一个视图

[Route("Account/Login/{clientname}", Name = ApplicationType.FRONTEND)]
[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true, Duration = 0)]
public async Task<IActionResult> TraineeLogin(string returnUrl)
{
  Return View();
}

我的 ajax 请求,虽然我只是在 div 选项卡点击时加载相关操作结果。

 $('#tabstrip a').click(function (e) {
            e.preventDefault();

            var tabID = $(this).attr("href").substr(1);
            localStorage.setItem("ClientCourseTab", '#'+tabID);
            $("#" + tabID).html("");
            var link = '@Url.Action("-1", "Course")';
            link = link.replace("-1", tabID);
            $("#" + tabID).load(link); // here actual request made
            var appendValue = tabID.replace('_FrontEnd', '');
            var appendValue = appendValue.replace('_', '');
            window.location.hash = appendValue;
            $(this).tab('show');
        });

感谢任何帮助!

在这种情况下,服务器对 ajax 请求执行 return 重定向响应,但用户不会被重定向到登录页面。为什么?原因是 HTTP 重定向由浏览器隐式处理,实际上从未到达 ajax 成功回调 。浏览器处理重定向并提供带有重定向目标内容的 200 代码(在您的情况下为登录页面)。

这并不像听起来那么简单,解决方法很少,但所有这些都非常复杂。这是您可以尝试实施的一种解决方案:

How to manage a redirect request after a jQuery Ajax call

另一个解决方案是在每个页面的特定时间间隔javascript代码运行检查会话是否已过期(通过查询服务器使事情变得更加复杂)。每当此 javascript 代码检测到会话已过期时,应立即将用户带到登录页面,而不是等待 ajax 请求被触发。 查询服务器的问题是,如果您在服务器上有某种滑动过期的授权票证,票证可能会被续订并且会话可能永远不会过期。