【问题标题】:User should be signed-out from application if user session is expired on server如果用户会话在服务器上过期,用户应该从应用程序中注销
【发布时间】:2013-01-28 15:13:51
【问题描述】:

我正在开发 Asp.net MVC 3 应用程序,其中我有一种在帐户控制器中注销的方法。

 public ActionResult LogOff()
        {
            try
            {
               // Session.User = null;

                this._authenticationService.SignOut();

                return RedirectToAction("Login", "Account");
            }
            catch (Exception e)
            {

                return View("Error");
            }
        }

我想从 global.asax.cs 中的 Session_End 方法调用这个方法,或者有没有其他方法可以从 global.asax.cs 文件中调用RedirectToAction("Login", "Account");

【问题讨论】:

标签: c# asp.net asp.net-mvc-3 session session-state


【解决方案1】:

您需要使用基于 Ajax+JavaScript 的解决方案,只需查看对您有帮助的类似线程:

Client-side session timeout redirect in ASP.Net

【讨论】:

    【解决方案2】:

    在 Global.asax.cs 文件中这样尝试:

    protected void Session_End()
        {
            // Clear the error on server. 
            Server.ClearError(); 
            Response.Clear(); 
    
            RouteData routeData = new RouteData(); 
    
            routeData.Values.Add("controller", "Account"); 
            routeData.Values.Add("action", "Login"); 
    
    
            // Call target Controller and pass the routeData. 
            IController AccountMainController = new AccountController(); 
            AccountMainController.Execute(new RequestContext( 
                    new HttpContextWrapper(Context), routeData));
        }
    

    【讨论】:

    • 在 Response.Clear() 行,我的调试器控件从应用程序中退出,下一行没有执行。
    • 你能把那行删掉试试看
    • 在 var rc = new RequestContext(new HttpContextWrapper(Context), routeData);同样的事情正在发生......
    • new HttpContextWrapper(Context) 抛出 ArgumentNullException 异常
    • new HttpContextWrapper(HttpContext.Current), HttpContext.Current 也为空
    【解决方案3】:

    “Session_End”不对应任何请求或任何请求流,因此重定向/执行控制器操作不会将 HTML 返回到浏览器。只要浏览器向服务器发出请求,几乎没有机会执行“Session_End”。可能您可以使用存储在会话中的对象,当会话结束时,该对象将从会话存储中丢弃。

    在 Begin_Request 事件或 MVC 中的全局过滤器中编写通用代码可以检查该对象是否存在,并可以在需要时重定向用户以注销操作。

    【讨论】:

      【解决方案4】:

      我不知道您是否可以在当前项目中使用 signalr,但如果可以,如果会话过期,您可以使用 signalr 在客户端调用重定向。

      服务器端类似的东西:

      protected void Session_End()
      {
          GlobalHost.ConnectionManager.GetHubContext<ConnectionStateHub>().Clients[{yourClientsId}].SessionExpired({yourRedirectTarget});
      }
      

      在客户端,类似以下的内容可以进行重定向:

      var sessionHub = $.connection.sessionHub;
      sessionHub.sessionExpired = function(target) { window.location = target; }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-14
        • 2018-03-01
        • 2020-09-06
        • 1970-01-01
        • 2011-05-15
        相关资源
        最近更新 更多