Question:

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

I Tried:

我try 对控制器类和单个操作使用多个路由属性,但没有成功.

Notes:

  • 我正在使用ASP.NET Core 1.0 RC1.

  • 一百

Example:

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

推荐答案

在控制器级别具有两个路由属性在新的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,可能需要设置属性的名称/顺序属性.

在动作上有两个属性也有效:

[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" });
    }
}

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

最后,另一种 Select 是使用新路由的属性,然后使用启动类中的路由表来提供照顾旧API的特定路由.

Asp.net相关问答推荐

ASP .Net Web API 将图像下载为二进制

如何注册路由区域

ASP.NET - 在屏幕底部显示应用程序构建日期/信息

ASP.NET 如何将控件呈现为 HTML?

下载功能在 asp.net 的更新面板中不起作用

控制器 SessionStateBehavior 是只读的,我可以更新会话变量

UseSqlServer 方法缺少 MVC 6

每月的每一天

返回 IHttpActionResult vs IEnumerable vs IQueryable

如何从 JS 访问 ViewBag

IIS 中的 existingResponse="PassThrough" 是什么意思?

从命令行复制 VS2008发布网站

使用 Ninject OWIN 中间件在 OWIN 启动中注入 UserStore

ASP.NET web.config:system.web.compilation 中的 debug 属性的默认值是什么?

Html.RenderAction 和 Html.Action 的区别

带有模型的 ASP.NET MVC 重定向

ASP.NET 5、EF 7 和 SQLite - SQLite 错误 1:没有这样的表:博客

ASP.NET MVC 5 Web.config:FormsAuthenticationModule或FormsAuthentication

ASP.NET 5 (vNext) - 获取配置设置

ASP.NET MVC2/3 中runAllManagedModulesForAllRequests的正确用法是什么?