Which redirect takes precedence - the one in the controller action or in the ActionFilter OnActionExecuted?

Looks like I'm going to do something strange again ...

Situation:

public ExperimentAttribute
{
    public override void OnActionExecuted (ActionExecutingContext filterContext)
    {
        filterContext.Result =
                    new RedirectToRouteResult (
                        new RouteValueDictionary (new { Action = "Action2", Controller = "Experiment" }));
    }
}

public ExperimentController
{
    [Experiment]
    public ActionResult ExperimentEntryPoint ()
    {
        RedirectToAction ("Action1", "Experiment");
    }

    public ActionResult Action1 ()
    {
        /* ... */
    }

    public ActionResult Action2 ()
    {
        /* ... */
    }
}

      

So what kind of redirection will take place? The one in the controller action, the one in the ActionFilter, or perhaps both?

+1


source to share


3 answers


So, I just ran an experiment that confirmed what I was expecting.

ExperimentEntryPoint returns an ActionResult, namely a redirect to Action1.



OnActionExecuted overwrites the result until the rest of the structure processes it. When it comes to him, he sees a redirect to Action2 command.

Nice and clear.

+1


source


I can't think of a reason (YET!) I can think of several reasons why you can do this in OnActionExecuting (), before your action code is executed) to change the ActionResult using filterContext.Result in the OnActionExecuting () method. but this is definitely allowed.

Execution order:

  • OnActionExecuting ()
  • Your action code in your controller
  • OnActionExecuted ()
  • OnResultExecuting ()
  • Regardless of the assigned ActionResult.ExecuteResult () returns (displays view, json, content, etc.)
  • OnResultExecuted ()

As your experiment showed you can change filterContext.Result in both OnActionExecuted () and OnActionExecuting (). Since OnActionExecuted () is called after your controller code (ex: return RedirectToAction ()), what it sets is because ActionResult takes precedence.



I found decent coverage of ActionFilters in Stephen Sanderson's About the ASP.NET MVC Framework. [12]

[1] http://books.google.com/books?id=Xb3a1xTSfZgC (Content in ActionFilters is not available in Google Book Preview)

[2] http://blog.codeville.net/2009/04/29/now-published-pro-aspnet-mvc-framework-apress/

+1


source


They cannot both happen as they both return an HTTP 302 redirect.

The attribute will do the redirection as it is the last thing that needs to happen before the result is sent to the client. Both OnActionExecuting and OnActionExecuted will execute on top of the result of the controller action.

0


source







All Articles