How to prevent execution of controller actions based on condition?

asp.net, asp.net-mvc, asp.net-mvc-3, asp.net-mvc-4, c#

Solution

This is a quick mock up, but I think the idea holds

public class CheckSessionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.HttpContext.Session["MyObject"] == null)
        {
            // redirect must happen OnActionExecuting (not OnActionExecuted)
            filterContext.Result = new RedirectToRouteResult(
              new System.Web.Routing.RouteValueDictionary {
              {"controller", "Tools"}, {"action", "CreateSession"}

        }
        base.OnActionExecuting(filterContext);
    }   
}

Problem

I have a controller with many actions. I need to prevent execution of some actions based on this condition: ``` if (Session["MyObject"] == null) return RedirectToAction("Introduction"); ``` It should redirect to a default Introduction action. I can put this condition in each action, but I would like to define this condition just in one place, like in controller's constructor maybe. Any ideas? Thank you.

Original source