I am trying to use OnActionExecuting in my BaseController to handle redirecting to LogOn screen if the User Session is timed out. However it is causing infinite redirects even before I get Logged in- Can anyone advise on how to get round this?
So in my Base controller I have the following:
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (SessionManager.Instance().GetUser() == null)
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary {
{ "Controller", "Home" },
{ "Action", "LogOn" }
});
}
base.OnActionExecuting(filterContext);
}
So basically I have a Session Manager class that can get/set a user etc - I kind of know the problem in that GetUser will also be null as it is only set using my SetUser method after LogOn has been validated.
But rather than having every method in my other controllers having a check like:
public ActionResult SomeOtherMethod()
{
if(SessionManager.Instance().GetUser() != null)
{
//Go Do Useful View stuff
}
else
{
//Redirect To Logon
}
}
I wanting to use OnActionExcuting in the Base Controller. But because it is running on the LogOn pages (as it should) I am getting infinte redierct because the GetUser will always be null?
Is there a better way off doing this
解决方案
Maybe you can try something like this :
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);
}