简体   繁体   English

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

[英]WebAPI controller same action different parameters

I have a base controller as with 2 actions: 我有2个动作的基本控制器:

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

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

Some of my controllers use the different Find method, for example: 我的某些控制器使用不同的Find方法,例如:

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

However, I get an error when calling this action from the client: 但是,从客户端调用此操作时出现错误:

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

How can I solve this problem? 我怎么解决这个问题?

The only way to solve this is by changing the ActionName attribute for one of the actions. 解决此问题的唯一方法是更改​​其中一个操作的ActionName属性。

ASP.NET MVC /Web API doesn't support two actions with the same name and same HTTP verb in the same controller. ASP.NET MVC / Web API在同一控制器中不支持两个具有相同名称和HTTP动词的操作。

Also take a look at this question ( ASP.NET MVC ambiguous action methods ) if you want to go for the 'hack solution' (my opinion). 如果您想寻求“黑客解决方案”(我认为),也可以看看这个问题( ASP.NET MVC歧义操作方法 )。

Why don't you just pass both parameters to the same action method? 为什么不将两个参数都传递给相同的操作方法? And inside your method simply check if they are null and do something about it. 在您的方法内部,只需检查它们是否为null并对其进行处理。

Use string and int? 使用字符串和整数? (nullable int) to allow both parameters to contain nulls. (nullable int)允许两个参数都包含null。

This way you get to use one view without any attribute jiggery pockery. 这样,您就可以使用一个没有任何属性的视图。

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 (ie the unique database key). 从资源集合中选择一个元素的动作应沿着资源的键(即唯一数据库键)进行。 This key can be either of type int or alphanum, but not both. 该键可以是int或alphanum类型,但不能两者都选。

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. 筛选器参数应作为查询字符串参数传递给REST端点。

Examples: 例子:

  1. /api/employees → returns resource set with all employees / api / employees→返回所有员工设置的资源
  2. /api/employees/5 → returns single resource (one employee) / api / employees / 5/5→返回单一资源(一名员工)
  3. /api/employees?name=john → returns resource set with all employees named "john" / api / employees?name = john→返回所有名为“ john”的员工的资源集

Example 3 is a filter, and I guess at least one of your finds is just that. 示例3是一个筛选器,我想您至少发现了一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM