Things I Learned Today - our daily eureka-moments

Programming .NET VS2010 Web Windows VS2012 S3 Search SQL SqlMetal Accessibility Amazon Android App BBQ EBS EC2 Exchange Food Garmin Geocaching GPS Grill Java Linq Lucene MVC PowerShell

You don't Response.Redirect() from an ActionFilterAttribute - Carr, 17.08.2011

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("/");

And now I know that, too.
Tags: .Net MVC Programming
Nobody has commented on this post yet. Feel free to be the first!