This week I had to use dotPeek on the Web Api to understand how the framework selects the controller method (action) that gets executed. The process is not complicated but I thought it might help other people if I documented my findings.
There's also a post on the asp.net website that talks about the web api rounting, check it out here.
The diagram below tries do describe the decision process behind selecting the method of the controller that will get executed. I've added a little extra documentation through the annotations on the diagram.
1 Action Based
If the route defines the action parameter then the method selection will be based on the value of that parameter. The matching will be based on the method name or the method alias (A method in the controller may be aliased using the ActionName attribute).
All the matching methods are then filtered by verb. The filtering is done by attributes applied to the method (such as HttpGet). Only the methods that match the verb of the incoming request will be returned. Methods with no attributes will also be considered valid as they don’t have any attributes to allow filtration.
2 Verb Based
When the method selection is verb based we need to get the Http verb used in the request. The controller methods are then filtered in two ways:
- Get all the methods annotated with http verb attributes matching the http method in the request (attributes such as HttpGet or HttpPost);
- Get all the methods that have the prefix matching the http method in the request (PostBooks matches the Post verb);
3 Check Results Found
All the candidate methods returned by either the verb based or action based approach are then analyzed. If no candidates where found an exception is thrown. If multiple methods were found it’s necessary to analyze it’s parameters to find out the best possible fit.
4 Find Route by Parameters
The parameters from the route and the parameters from the query string are compared to the method's parameters. If no parameters are found in the query string or in the route, all methods without parameters will be selected. If multiple methods match the parameters found, the ones that take the most parameters will win. Here is a diagram that details this specific part of the process:
5 Selection Filters
The last filters executed on the candidate methods will make sure that all methods marked with the NonAction attribute will be excluded.
I hope these diagrams were clear enough to help understand better the process of selecting the controller method that gets executed for a request.
blog comments powered by Disqus