WebAPI控制器同样动作不同的参数

时间:2014-07-30 07:58:46

标签: c# asp.net-web-api

我有一个基本控制器和2个动作:

    [ActionName("Find")]
    [HttpGet]
    public virtual IHttpActionResult Find(string name)
    {
        return null;
    }

    [ActionName("Find")]
    [HttpGet]
    public virtual IHttpActionResult Find(int number)
    {
        return null;
    }

我的一些控制器使用不同的Find方法,例如:

    public override IHttpActionResult Find(string number)
    {
        return OK;   
    }

但是,从客户端调用此操作时出现错误:

Multiple actions were found that match the request: \r\nFind on type API.Controllers.CustomerController

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:4)

解决此问题的唯一方法是更改​​其中一个操作的ActionName属性。

ASP.NET MVC / Web API不支持在同一控制器中具有相同名称和相同HTTP谓词的两个操作。

如果您想要使用' hack解决方案,请查看此问题(ASP.NET MVC ambiguous action methods)。 (我的意见)。

答案 1 :(得分:1)

为什么不将两个参数都传递给同一个操作方法?在你的方法中,只需检查它们是否为空并对它做些什么。

使用string和int? (nullable int)允许两个参数都包含空值。

这样你就可以使用一个没有任何属性jiggery pockery的视图。

答案 2 :(得分:0)

I think, you should reconsider your endpoint structure:

An action that selects one element from a resource collection should do that along the key of the resource (i.e. the unique database key). This key can be either of type int or alphanum, but not both.

What you probably want to realize with one or both of your finds, is to establish a filter function. Filter parameters should be passed to REST endpoints as query string parameters.

Examples:

  1. /api/employees → returns resource set with all employees
  2. /api/employees/5 → returns single resource (one employee)
  3. /api/employees?name=john → returns resource set with all employees named "john"

Example 3 is a filter, and I guess at least one of your finds is just that.