【问题标题】:Microsoft.AspNetCore.Routing.Matching.AmbiguousMatchException: The request matched multiple endpointsMicrosoft.AspNetCore.Routing.Matching.AmbiguousMatchException:请求匹配多个端点
【发布时间】:2021-09-02 04:06:00
【问题描述】:

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

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

//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. 

这很明显和理解。

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

/api/customer/{id}

/api/customer/emai/{id}

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

但是这家伙有一个参数是 int 而另一个是 string 所以路由约束被救了。

但是,我看到有人在同一个帖子上发帖/建议添加[Route("")],但我不明白这个属性有什么用?

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

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

【问题讨论】:

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


    【解决方案1】:

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

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

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

    【讨论】:

    • 如果 id 是常规字符串会怎样
    • 那么也许您可以在第二个约束中添加email 约束?如果不是,这两个 不能 被消除歧义 - 如果两者都可以是 any string,ASP.NET Core 将如何知道调用哪个路由?
    猜你喜欢
    • 1970-01-01
    • 2020-11-24
    • 1970-01-01
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多