ASP.NET Core WebApi:AmbiguousMatchException:请求与多个端点匹配

时间:2020-08-04 08:46:44

标签: asp.net-web-api routes http-get

我在标准.NET Core WebApi项目中有此控制器代码:

[ApiController]
[Route("[controller]")]
public class MessageController : ControllerBase
{
  [HttpGet]
  public string GetByTransactionId([FromRoute(Name = "transactionId")] string transactionId)
  {
    return "transactionId";
  }

  [HttpGet]
  public string GetByNumber([FromRoute(Name = "number")] string number)
  {
    return "number";
  }
}

我想像这样访问api

  • https:// localhost:44316 / Message?transactionId = abc
  • https:// localhost:44316 / Message?number = foobar

当访问端点URL时,例如:https:// localhost:44316 / Message?transactionId = abc,我得到的错误是:

AmbiguousMatchException: The request matched multiple endpoints. Matches:

Server.Controllers.MessageController.GetByTransactionId (Server)
Server.Controllers.MessageController.GetByNumber (Server)

可以通过使用正确的[HttpGet][Route]属性来解决此问题吗?

1 个答案:

答案 0 :(得分:1)

    [ApiController]
    [Route("[Message]")]
    public class MessageController : ControllerBase
    {
      [HttpGet]
      [Route("transactionId")]
      public string GetByTransactionId([FromRoute(Name = "transactionId")] string transactionId)
      {
        return "transactionId";
      }
    
      [HttpGet]
      [Route("number")]
      public string GetByNumber([FromRoute(Name = "number")] string number)
      {
        return "number";
      }
    }

尝试使用Route-attribute。这将解决您的问题