OnActionExecuting导致无限重定向处理会话超时

我试图在我的BaseController中使用OnActionExecuting来处理重定向到LogOn屏幕,如果用户会话超时。 然而,即使在我登录之前它也会导致无限重定向 – 任何人都可以建议如何绕过这个?

所以在我的Base控制器中我有以下内容:

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,因为它仅在validation了LogOn后使用我的SetUser方法设置。

但是,而不是让我的其他控制器中的每个方法都检查如下:

 public ActionResult SomeOtherMethod() { if(SessionManager.Instance().GetUser() != null) { //Go Do Useful View stuff } else { //Redirect To Logon } } 

我想在基本控制器中使用OnActionExcuting。 但是因为它在LogOn页面上运行(因为它应该)我得到infinte redierct因为GetUser总是为null?

有没有更好的方法来做这件事

也许你可以尝试这样的事情:

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