0

我正在尝试设计 API 版本控制,但出现以下错误

多个动作匹配。以下操作匹配路线数据并满足所有约束

我不想复制所有控制器方法,而是只覆盖任何已更改但未更改的内容导致错误。这是我正在尝试的不好的做法吗?我的问题有什么解决方案吗?

[ApiVersion( "1.0" )]
[AllowAnonymous]
[Route("api/v{api-version:apiVersion}/[controller]")]
public class HeartbeatController : Controller
{
    [AllowAnonymous]
    [HttpGet, MapToApiVersion("1.0")]
    public virtual IActionResult Beat()
    {
        return Ok(DateTime.Now.ToString("HH:mm:ss"));
    }

    [AllowAnonymous]
    [HttpGet, MapToApiVersion("0.9")]
    public virtual IActionResult Get()
    {
        return Ok(Environment.MachineName);
    }
}


[ApiVersion("2.0")]
[AllowAnonymous]
[Route("api/v{api-version:apiVersion}/[controller]")]
public class HeartbeatController : V1.Controllers.HeartbeatController
{
    [AllowAnonymous]
    [HttpGet]
    public override IActionResult Get()
    {
        return Ok("this is version 2 " + Environment.MachineName);
    }
}
4

1 回答 1

1

继承可能很棘手,哪些属性是继承的,哪些不是继承的并不总是很明显。在这种情况下,RouteAttributeHttpGetAttribute是继承的,但ApiVersionAttribute不是。

以下配置将为您提供所需的内容:

using static System.Environment;

[ApiVersion( "1.0" )]
[Route( "api/v{api-version:apiVersion}/[controller]" )]
public class HeartbeatController : Controller
{
    [HttpGet]
    public virtual IActionResult Get() => Ok( MachineName );
}

[ApiVersion( "2.0" )]
public class HeartbeatController : V1.HeartbeatController
{
    public override IActionResult Get() => Ok( "this is version 2 " + MachineName );
}
于 2018-03-26T01:14:45.523 回答