I have inherited an application which uses Application_PreRequestHandlerExecute to redirect to login if the session has expired.
Currently there is a list of hard-coded urls which should not invoke a redirect. Essentially, these are ajax methods which return json, so they are dealt with separately in javascript.
I would like to change the mechanism so that the default (in Application_PreRequestHandlerExecute) remains the same but alternative behaviour can be controlled by ActionFilters on the appropriate Actions (i.e. those corresponding to the hard-coded list of urls).
How do I check for the presence of the particular ActionFilter in Application_PreRequestHandlerExecute?
EDIT: Perhaps I need to replace Application_PreRequestHandlerExecute with a Global Action Filter?
The short answer is to replace with a global Action Filter.
Within that, filterContext
has everything that I need.
EDIT: This is the gist of what I went for:
public enum SessionExpiredBehaviour
{
Redirect,
Ignore,
JSON
}
[AttributeUsage(AttributeTargets.Method)]
public class SessionExpiredFilterAttribute : ActionFilterAttribute
{
public SessionExpiredBehaviour Behaviour { get; set; } = SessionExpiredBehaviour.Redirect;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (HttpContext.Current.Session["User"] == null)
{
switch (this.Behaviour)
{
case SessionExpiredBehaviour.Redirect:
filterContext.Result =
new RedirectToRouteResult(new RouteValueDictionary
{
{ "action", "RedirectToLogin" },
{ "controller", "Account" }
});
break;
case SessionExpiredBehaviour.JSON:
//TODO
break;
}
}
base.OnActionExecuting(filterContext);
}
}