2013-02-21 94 views
2

我想在我的BaseController中使用OnActionExecuting處理重定向到登錄屏幕,如果用戶會話超時。然而,即使在登錄之前,它也會導致無限的重定向 - 任何人都可以提供如何解決這個問題的建議?OnActionExecuting導致無限重定向處理會話超時

所以在我的基地控制器我有以下幾點:

protected override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     if (SessionManager.Instance().GetUser() == null) 
     { 
      filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { 
        { "Controller", "Home" }, 
        { "Action", "LogOn" } 
      }); 
     } 

     base.OnActionExecuting(filterContext); 
    } 

所以基本上我有一個可以獲取/設置用戶等一個會話管理器類 - 我那種知道該的getUser問題也將是null,因爲它只是在LogOn驗證後使用我的SetUser方法設置的。

但是,而不是我在其他控制器的每個方法具有象檢查:

public ActionResult SomeOtherMethod() 
{ 
    if(SessionManager.Instance().GetUser() != null) 
    { 

      //Go Do Useful View stuff 

    } 
    else 
    { 
      //Redirect To Logon 
    } 

} 

我想在基本控制器使用OnActionExcuting。但是因爲它在LogOn頁面上運行(因爲它應該)我得到infinte redierct,因爲GetUser將始終爲空?

有沒有更好的路要走這樣

回答

3

也許你可以嘗試這樣的事:

protected override void OnActionExecuting(ActionExecutingContext filterContext) 
{ 
    string controllerName = filterContext.Controller.GetType().Name; 
    string actionName = filterContext.ActionDescriptor.ActionName; 

    if (SessionManager.Instance().GetUser() == null) 
    { 
     if(!controllerName.Equals(typeof(HomeController).Name,StringComparison.InvariantCultureIgnoreCase) 
     || !actionName .Equals("LogOn",StringComparison.InvariantCultureIgnoreCase))) 
     filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { 
       { "Controller", "Home" }, 
       { "Action", "LogOn" } 
     }); 
    } 

    base.OnActionExecuting(filterContext); 
} 
+0

好 - 我會嘗試,看看它是如何去。感謝您的迴應。 – 2013-02-21 11:24:12