c# - Microsoft.AspNetCore.Routing.Matching.AmbigouslyMatchException : The request matched multiple endpoints

标签 c# asp.net-core asp.net-core-3.1

我有一个 ASP.Net Core WebAPI,我得到了以下要求

我有两种方法来处理 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/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="afc2d6cac2cec6c3efc8c2cec6c381ccc0c2" rel="noreferrer noopener nofollow">[email protected]</a>
[HttpGet("{name}")]
public async Task<ActionResult<Customer>> GetCustomerByEmail([FromRoute]string email) 
{
   
}

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

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

这是非常明显和理解的。

可以通过在路由中附加/前置一些字符串来轻松解决这个问题,例如

/api/customer/{id}

/api/customer/emai/{id}

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

但是这个家伙有一个参数为 int,而另一个参数为 string,因此路由约束被拯救。

但是,我看到有些人在同一篇文章中发帖/建议添加 [Route("")] 但我不明白此属性有何用处?

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

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

最佳答案

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

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

[HttpGet("{name}")]

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

关于c# - Microsoft.AspNetCore.Routing.Matching.AmbigouslyMatchException : The request matched multiple endpoints,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68017873/

相关文章:

c# - 如何在 SQLite.net 中存储对象列表?

c# - 在 C# 中删除 flowlayoutpanel 中的所有控件

asp.net-core - 使用 ASP.NET Core 2.1 Identity 进行基于权限的授权

c# - 集成测试 .NET Core 3 Worker

c# - 无法访问已处置的上下文实例

c# - 具有内部构造函数的最小起订量具体类

c# - C#线程示例代码在没有锁的情况下工作

azure - Microsoft.Identity.Web 和 ASP.NET Core SignalR JWT 身份验证

c# - 内存中集成测试和环境变量——.net core

c# - 为什么这个 View 模型字符串字段被视为必需的?