【问题标题】:Handling session timeout in mvc在 mvc 中处理会话超时
【发布时间】:2017-10-06 12:26:28
【问题描述】:

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

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

中间件

 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 请求,您也希望将用户重定向到登录页面?
  • 是的,如果会话超时,用户应该被重定向到 ajax 请求中的登录页面

标签: c# ajax asp.net-core asp.net-core-mvc session-timeout


【解决方案1】:

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

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

How to manage a redirect request after a jQuery Ajax call

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

【讨论】:

  • 非常感谢您的帮助!它真的帮助了我!
猜你喜欢
  • 2012-11-10
  • 2016-03-27
  • 2011-09-25
  • 2019-08-16
  • 2012-08-16
  • 1970-01-01
  • 2018-04-19
  • 1970-01-01
  • 2012-09-16
相关资源
最近更新 更多