我有一个 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/