在 ASP MVC 6 中将多个路由分配给同一控制器或操作

Assigning multiple routes to the same controller or action in ASP MVC 6

问题:

有没有办法在 ASP.NET MVC 6 应用程序中将两条不同的路由(带参数)分配给同一个控制器?

我试过了:

我尝试对控制器 class 和单个操作使用多个路由属性,但没有用。

备注:

示例:

[Produces("application/json")]
[Route("api/v2/Log")]
/// The old route is "api/LogFile" which I want to be still valid for this controller.
public class LogController : Controller {
    [HttpGet("{id}", Name = "download")]
    public IActionResult GetFile([FromRoute] Guid id) 
    {
        // ...
    }
}

在上面的例子中:api/LogFile/{some-guid}是旧路由,api/v2/log/download/{some-guid}是新路由。我需要两条路线调用相同的动作。

在控制器级别有 2 个路由属性在新的 RC1 应用程序中工作正常:

[Produces("application/json")]
[Route("api/[controller]")]
[Route("api/old-log")]
public class LogController: Controller
{
    [HttpGet]
    public IActionResult GetAll()
    {
        return Json(new { Foo = "bar" });
    }
}

http://localhost:62058/api/loghttp://localhost:62058/api/old-log return 都是预期的 json。我看到的唯一警告是,您可能需要设置属性的 name/order 属性,以防您需要为这些操作之一生成 url。

动作有 2 个属性也有效:

[Produces("application/json")]        
public class LogController : Controller
{
    [Route("api/old-log")]
    [Route("api/[controller]")]
    [HttpGet]
    public IActionResult GetAll()
    {
        return Json(new { Foo = "bar" });
    }
}

但是,在控制器级别具有通用路线和特定操作路线时,您需要小心。在这些情况下,控制器级别的路由用作前缀并添加到 url 之前(有一篇关于此行为的好文章 here)。这可能会给您带来与预期不同的一组 url,例如:

[Produces("application/json")]
[Route("api/[controller]")]
public class LogController : Controller
{
    [Route("api/old-log")]
    [Route("")]
    [HttpGet]
    public IActionResult GetAll()
    {
        return Json(new { Foo = "bar" });
    }
}

在最后一种情况下,您的应用程序将侦听的 2 条路由是 http://localhost:62058/api/loghttp://localhost:62058/api/log/api/old-log,因为 api/log 作为前缀添加到在操作级别定义的所有路由。

最后,另一种选择是使用新路由的属性,然后在启动 class 中使用路由 table 来提供处理旧路由的特定路由 api.