0

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?

4

1 回答 1

2

您似乎正在尝试做一些类似于自定义参数绑定的好博客文章中描述的事情。正如您所发现的,没有开箱即用的东西可以支持您尝试做的事情。

在概念层面上,HTTP 是围绕资源的概念构建的。URI 应该标识一个特定的资源。使用通用位置“参数”似乎模糊了资源的特殊性。使用 URI 的查询字符串似乎可以更好地服务于您的用例。这样,您的 HTTP API 就可以清楚地表达给定资源的预期参数的意图。

于 2013-01-28T15:06:52.167 回答