Choosing the Right Actions
Excerpt by Phil Ledgerwood | August 02, 2013
The job of the action invoker to select the appropriate action method is more complicated than may appear on the surface. There could be multiple overloaded methods with the same name in a controller, they may be decorated with different attributes that make their selection appropriate in some scenarios and not others, their action method name may be different from their class method name, and other complications. Designing an effective controller requires that you understand how the selection process works. The first thing that the action invoker does is to look for the action portion of the route definition for the request. Using the default route defined in a new MVC application shown below, it is the name at the second position.
Even if the current URL doesn't include the action portion of the route, the default route definition defines it to be the "Index" action. Once the action invoker has the name of the action, it needs to map that action name to a method of the controller. The simplest case occurs when there is a single method in the controller class with a name that matches the action name. For example, in a new MVC application the Index action of the Home controller maps to the single Index method in that controller. But what qualifies as an action method? Is every method defined in the controller a potential action method? Not at all. There are a few requirements that a method must meet for the action invoker to consider it to be an action method candidate:
- It must be a public method and not marked as static.
- It cannot be a method defined on System.Object or the Controller base class. In other words, it must be defined within your custom controller object, not inherited from another object. So ToString could not be an action method because it is defined on System.Object.
- It cannot be a special method, such as a constructor, property accessor, or event accessor.
- It cannot have the NonActionAttribute decoration. This attribute is handy if you want to include a public method in a controller but don't want to use it as an action method.
Taking all these restrictions into consideration, the action invoker uses reflection to find all methods in the controller with the same action name as the action name specified in the URL and meet the previous requirements. But here is where things get a bit murky. Through the use of attributes on the controller's methods, there could be multiple methods with the same name, the action name could be different from the method name, and there may be a selector attribute that restricts which requests an action method can respond to. This can create a bit of a gauntlet that the action invoker must navigate in order to find the correct action method.