Currently we use the below routing rules to cater for all our controllers; the advantage being that we don’t have to define a route for each action in each controller:
routes.MapHttpRoute("3", "{controller}/{action}/{arg1}/{arg2}/{arg3}");
routes.MapHttpRoute("2", "{controller}/{action}/{arg1}/{arg2}");
routes.MapHttpRoute("1", "{controller}/{action}/{arg1}");
routes.MapHttpRoute("0", "{controller}/{action}");
However due to this the parameter names in the methods must match; like so:
// Example method signature
public ResponseDto GetResponse(int arg1, int arg2)
If the parameter names are changed to something more friendly (eg: a name that would show the intention of each parameter instead of an ambiguous “arg1” name) like so:
// Better example method signature
public ResponseDto GetResponse(int userId, int itemId)
The binding would break unless:
- The routes and parameter names are explicitly defined
- The arguments are passed in using a query string
Is there are way to set up WebApi routing so it will automatically use the correct action based on the number of parameters; rather than the parameter names?
It seems you’re trying to do something similar to what is described in this good blog post on custom parameter binding. As you’ve found out, there is nothing out-of-the-box to support what you’re trying to do.
At a conceptual level, HTTP is built around the concept of resources. A URI should identify a specific resource. Using generic positional “parameters” seems to blur the specificity of a resource. It seems that your use case might be better served by using the query string of the URI. That way, your HTTP API expresses a clear intent of what parameters are expected for a given resource.