简体   繁体   English

在MVC中处理会话超时

[英]Handling session timeout in mvc

I am trying to implement session timeout in .net core application. 我正在尝试在.net核心应用程序中实现会话超时。 Redirecting to login page is working fine in non-ajax request/full postback but not in case of ajax request. 在非ajax请求/完整回发中,重定向到登录页面可以正常工作,但在ajax请求的情况下则无法正常工作。 The login page is displayed within the layout/current page in ajax request. 登录页面显示在ajax请求的布局/当前页面内。

I have written a middleware which will call the controller method first in which redirection login is written.Below is my code. 我编写了一个中间件,它将首先调用控制器方法,并在其中编写重定向登录。以下是我的代码。

Middleware 中间件

 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();
                }
            });

Home Controller 家庭控制器

[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();
        }

and in Login method I am just returning a 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();
}

My ajax request , though I am just loading related action results in div on tab click. 我的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');
        });

Any help on this appreciated ! 任何对此的帮助表示赞赏!

The server does return the Redirect response in this case for the ajax request but the user doesn't get redirected to the Login page. 在这种情况下,服务器确实会为ajax请求返回Redirect响应,但不会将用户重定向到Login页面。 Why? 为什么? The reason is that the HTTP redirect is implicitly processed by the browser and actually never arrives to the ajax success callback . 原因是HTTP重定向是由浏览器隐式处理的,实际上从来没有到达ajax成功回调 The browser processes the redirect and delivers a 200 code with the content of the redirect's destination (the login page in your case). 浏览器将处理重定向,并提供包含重定向目标内容(本例中为登录页面)的200代码。

This is not as simple as it sounds, there are few workarounds but all of those quite complicate things. 这并不像听起来那么简单,很少有解决方法,但是所有这些都非常复杂。 Here is one solution that you might try to implement: 这是您可以尝试实现的一种解决方案:

How to manage a redirect request after a jQuery Ajax call jQuery Ajax调用后如何管理重定向请求

Another solution can be to have some javascript code running at a specific interval on each page to check whether the session has expired (by querying the server which complicates things even more). 另一个解决方案是在每个页面上特定间隔运行一些javascript代码,以检查会话是否已过期(通过查询服务器,这会使事情更加复杂)。 Whenever this javascript code detects that the session has expired, user should be immediately taken to the login page instead of waiting for an ajax request to be triggered. 每当此javascript代码检测到会话已过期时,应立即将用户带到登录页面,而不是等待ajax请求被触发。 The problem with querying the server would be that if you have some kind of sliding expiration of auth ticket on the server , the ticket might get renewed and session might never expire. 查询服务器的问题是,如果服务器上的auth票证有某种滑动期限 ,则该票证可能会更新,并且会话可能永不过期。

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

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