Slava
Slava

Reputation: 6650

How to prevent execution of controller actions based on condition?

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.

Upvotes: 2

Views: 2680

Answers (1)

Dave Alperovich
Dave Alperovich

Reputation: 32510

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

Upvotes: 7

Related Questions