Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExecuteCore() vs OnActionExecuting(ActionExecutingContext filterContext)?

Tags:

c#

asp.net-mvc

Just curious, they sound similar. What are the differences between ExecuteCore() vs OnActionExecuting(ActionExecutingContext filterContext)?

In what situations would one be more useful over the other?

like image 244
Chaddeus Avatar asked Dec 14 '10 15:12

Chaddeus


2 Answers

Actually, they're just different points in MVC execution pipeline.

  1. ExecuteCore is called by MvcHandler after controller itself is instantiated. By this moment MVC doesn't even know about how controller will invoke its action. You can override standard Controller's ExecuteCore to tweak its overall execution process a little bit.

  2. OnActionExecuting is a completely different story. It is called during action filters invocation by ControllerActionInvoker. By that point MVC already knows that action exists, invokes it, obtains all filters (usually defined as attributes) and executes it in a given moment of overall execution pipeline (OnActionExecuting, OnActionExecuted, OnResultExecuting and so on).

It depends on what exactly you want to achieve when deciding what extension point to use.

  • Override ExecuteCore in derived Controller to tweak its common behavior (not really often the case in normal app).
  • Use filters to perform some additional tasks that seem orthogonal to what acion itself is supposed to do (often this is some AOP-like logic or relates to database session/transaction management).
like image 108
Vasiliy R Avatar answered Nov 14 '22 23:11

Vasiliy R


ExecuteCore is invoked just after the controller has been initialized while OnActionExecuting happens at a later stage of the execution pipeline and is called immediately before the controller action is invoked. In the second method you can directly manipulate the actionresult and short-circuit the execution of the action by redirecting for example to some other action:

filterContext.Result = ...
like image 26
Darin Dimitrov Avatar answered Nov 14 '22 21:11

Darin Dimitrov