2

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.

5
  • 1
    2 ideas. Custom Authorization filter or custom Action Filter. You can either populate the filter with logic that decides which action is affected or by which actions you apply the filter Commented Jan 30, 2013 at 17:57
  • I am a Java programmer so I could be wrong but wouldn't putting the code snippets you presented in the constructor result in all actions being redirected to the default introduction? Commented Jan 30, 2013 at 18:04
  • Sure, I need to distinguish between actions. I guess Dave's advice is correct. let me check.. Commented Jan 30, 2013 at 18:08
  • Only if the session object is empty. I assume the goal is to populate the session if it expires Commented Jan 30, 2013 at 18:10
  • Not really. The session object is not set automatically, there is some specific app logic for that. Doesnt matter ;) Thanks Dave, the ActionFilterAttribute suggestion is perfect !! Commented Jan 30, 2013 at 18:24

1 Answer 1

7

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);
    }   
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.