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

时间:2018-03-05 01:05:20

标签: c# asp.net-core-2.0 api-versioning

我正在尝试设计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);
    }
}

1 个答案:

答案 0 :(得分:1)

继承可能很棘手,并不总是很明显哪些属性是继承的,哪些属性不是。在这种情况下, RouteAttribute HttpGetAttribute 会被继承,但 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 );
}