Microsoft.AspNetCore.Routing.Matching.AmbiguousMatchException: 请求匹配多个端点

Microsoft.AspNetCore.Routing.Matching.AmbiguousMatchException: The request matched multiple endpoints

我有一个 ASP.Net 核心 WebAPI,我的要求低于

我有 2 种方法来处理 HTTP GET 请求,第一种通过 id(string) 获取 GetCustomer,另一种通过电子邮件(string) 获取 GetCustomer。

//GET : api/customers/2913a1ad-d990-412a-8e30-dbe464c2a85e
[HttpGet("{id}")]
public async Task<ActionResult<Customer>> GetCustomer([FromRoute]string id) 
{
   
}

// GET: api/customers/myemail@gmail.com
[HttpGet("{name}")]
public async Task<ActionResult<Customer>> GetCustomerByEmail([FromRoute]string email) 
{
   
}

当我尝试访问此端点时,出现异常:

Microsoft.AspNetCore.Routing.Matching.AmbiguousMatchException: The request matched multiple endpoints. 

这是很明显和理解的。

它可以通过 appending/prepending 路由中的一些字符串轻松解决,例如

/api/customer/{id}

/api/customer/emai/{id}

但是我不太相信这个方法但是在谷歌搜索上我得到了下面的 SO link

但是这家伙有一个参数是 int 而另一个是字符串所以路由约束得救了。

不过,我看到有人posting/suggesting在同一个post上添加[Route("")]但是我没明白这个属性有什么用?

afaik,Route("")HTTPGet("") //任何 HttpVerb 都有相同的目的?

无论如何,我怎样才能优雅地处理我的要求?

您可以添加 route constraints 来消除两条路线之间的歧义:

[HttpGet("{id:guid}")]

[HttpGet("{name}")]

您还可以创建自己的 email 约束或对电子邮件参数使用 regex(.) 约束。