重用一个函数来处理两个不同的数据类型作为第二个参数

本文关键字:数据类型 参数 第二个 处理 一个 函数 两个 | 更新日期: 2023-09-27 18:28:27

我必须更改我的控制器来处理2个不同的查询字符串,但参数数量相同,所以我似乎不能有两个具有相同名称和参数数量的函数:

错误

The current request for action 'FollowUp' on controller type 'ContactController' is ambiguous between the following action methods:

那么我该怎么做呢?

*字符串#1字符串,int*?contacted=true&id=7889876

字符串#2字符串,字符串?contacted=true&pid=AWRE-9876-POKJ-112WQ

电流控制器

 [HttpGet]
 public ActionResult FollowUp(string contacted, int id) {}

谢谢!

重用一个函数来处理两个不同的数据类型作为第二个参数

与其创建两个函数,不如创建一个带有三个参数的函数,并相应地使用您的逻辑。

示例:

[HttpGet]
public ActionResult FollowUp(string contacted, string pid, int? id) 
{
   if(!string.IsNullOrEmpty(contacted) && !string.IsNullOrEmpty(pid)) {
      // do your logic.
   }
   else if(!string.IsNullOrEmpty(contacted) && id != null) {
      // do your logic.
   }
}

注意:id作为nullable不需要任何值形式的URL。如果不将任何内容传递给此参数,它将为null。

希望这会有所帮助。

不能有多个具有相同名称的操作可以响应GET请求。您还可以将另一个参数添加到您的操作中,并通过检查存在哪些参数来决定要执行的操作。

[HttpGet]
public ActionResult FollowUp(string contacted, int? id, string pid) {}