In a recent ASP.NET MVC3 project, I was decorating some controller actions with an ActionFilterAttribute. The filter was supposed to check for a couple of requirements before allowing actions to execute.
Coming from webforms and being reasonably new to MVC3, I assumed the following would work:
public class CheckSomething : ActionFilterAttribute
{
public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext)
{
filterContext.HttpContext.Response.Redirect("/", true);
}
}
If a controller uses this filter, the filter should redirect the user and end the response right there. Just like good old times, right? Wrong.
Yes, this will redirect the user, but it will also let the calling controller action complete its execution first.
In MVC land, the filter will have to change filterContext.Result in order to halt execution of the calling action. This works:
public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext)
{
filterContext.Result = new RedirectResult("/");
return;
}
And now I know that, too.