asp.net - 在 ASP MVC 6 中将多个路由分配给同一 Controller 或操作

标签 asp.net asp.net-core asp.net-core-mvc

问题:

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

我尝试过:

我尝试对 Controller 类以及单个操作使用多个路由属性,但没有成功。

注释:

  • 我使用的是 ASP.NET Core 1.0 RC1。

  • 我想要这样做的原因是,我希望 API 与使用旧 URL 的旧版本移动应用程序兼容。

示例:

[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} 是新路线。我需要两条路线调用相同的操作。

最佳答案

在 Controller 级别拥有 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 都返回预期的 json。我看到的唯一警告是,您可能需要设置属性的名称/顺序属性,以防您需要生成这些操作之一的 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" });
    }
}

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

[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 作为前缀添加到在操作级别定义的所有路由。

最后,另一种选择是使用新路由的属性,然后使用启动类中的路由表来提供处理旧 API 的特定路由。

关于asp.net - 在 ASP MVC 6 中将多个路由分配给同一 Controller 或操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35296018/

相关文章:

html - 最小化 ul 以戏剧性的方式改变 li

javascript - HeaderTemplate 中的 CheckBox 验证 ItemTemplate CheckBox

asp.net-core - 如何使用自定义服务在 ASP.NET Core 3.1 中注册身份验证提供程序?

c# - AspNetCore 无法加载类型 'Swashbuckle.AspNetCore.SwaggerGen.SwaggerResponseAttribute'

c# - 如何解决服务层内部的循环依赖

c# - 在 Asp.Net Core 3.0 中禁用身份验证以进行开发

asp.net - 在 ASP.NET 5 中,如何在中间件中获取所选路由?

linux - 如何在 AWS Linux 实例上运行 .NET Core MVC 站点

asp.net-mvc - 在 ASP.NET Core 2.2 MVC 和 Identity 中设置登录路径

c# - 一个 ASP.net 网站/项目可以有超过 1 个数据库吗?