Web API 2属性路由:AmbiguousMatchException:请求与多个端点匹配

时间:2020-04-23 11:26:11

标签: routes asp.net-web-api2 asp.net-core-webapi swagger-ui

您好,以下是我的情况

我有带有方法CreatePerson的PersonController

[ApiVersion(ApiControllerVersion.Version1)]
    public class PersonController : BaseController
    {
        [HttpPost]
        [Route("/person")]
        [Produces("application/json")]
        [SwaggerResponse((int)HttpStatusCode.OK)]
        [SwaggerResponse((int)HttpStatusCode.InternalServerError, Type = typeof(ErrorServiceResponse))]
        [SwaggerResponse((int)HttpStatusCode.BadRequest, Type = typeof(ErrorServiceResponse))]
        [SwaggerOperation("POST: Create Person")]
        [ValidateModelState]
        public async Task<IActionResult> CreatePerson([FromBody][Required] CreatePersonRequest person)
        {
        }

        [HttpPut]
        [Route("/person")]
        [Produces("application/json")]
        [SwaggerResponse((int)HttpStatusCode.OK)]
        [SwaggerResponse((int)HttpStatusCode.InternalServerError, Type = typeof(ErrorServiceResponse))]
        [SwaggerResponse((int)HttpStatusCode.BadRequest, Type = typeof(ErrorServiceResponse))]
        [SwaggerOperation("POST: Change Person")]
        [ValidateModelState]
        public async Task<IActionResult> UpdatePerson([FromBody][Required] UpdatePersonRequest person)
        {
        }
    }

我想创建此API的另一个版本,如下所示,因为我的创建路线已更改。 我要继承PersonController的地方,我需要V1的所有方法,而v2除外的所有方法(“ CreatePerson”除外)

[ApiVersion(ApiControllerVersion.Version2)]
    public class PersonControllerV2 : PersonController
    {
        [HttpPost]
        [Route("/persons")]
        [Produces("application/json")]
        [SwaggerResponse((int)HttpStatusCode.OK)]
        [SwaggerResponse((int)HttpStatusCode.InternalServerError, Type = typeof(ErrorServiceResponse))]
        [SwaggerResponse((int)HttpStatusCode.BadRequest, Type = typeof(ErrorServiceResponse))]
        [SwaggerOperation("POST: Create Person")]
        [ValidateModelState]
        public new async Task<IActionResult> CreatePerson([FromBody][Required] CreatePersonRequest person)
        {
        }
    }

如果我不更改路线,则可以看到V1 POST / person和V2 POST / person运行正常

当我按照我的要求将CreatePerson的V2路由从“ / person”更改为“ / persons”时,我从招摇中调用V1 POST / person时出现错误消息

Microsoft.AspNetCore.Routing.Matching.AmbiguousMatchException:请求与多个端点匹配。 Controllers.PersonControllerV2.CreatePerson Controllers.PersonController.CreatePerson

在这种情况下,我的

V1摇头秀

  • POST /人
  • 放置/人

V2大摇大摆

  • POST /人
  • POST /人
  • 放置/人

有任何解决此问题的想法或建议吗?

1 个答案:

答案 0 :(得分:0)

原因是因为您没有在[ApiController][ApiVersion(ApiControllerVersion.Version1)]之前指定[ApiVersion(ApiControllerVersion.Version2)]

所以您应该这样更改:

[ApiController] 
[ApiVersion(ApiControllerVersion.Version1)]
    public class PersonController : BaseController
    {...

[ApiController] 
[ApiVersion(ApiControllerVersion.Version2)]
    public class PersonControllerV2 : PersonController
    {...