代码之家  ›  专栏  ›  技术社区  ›  Ben

如何使用标记助手创建到在路由属性中使用斜线的控制器/操作的链接?

  •  0
  • Ben  · 技术社区  · 8 年前

    在我开始之前,我知道有类似的问题,但它们都与在路由中使用参数斜线有关,而这不是我想要实现的(至少还没有实现)。

    我正在创建一个ASP.NET核心2 MVC Web应用程序,并且在创建指向我的操作的链接时,我的路由中的斜线被转义了。我有以下控制器:

    [Route("Manage/Account")]
    public class AccountsController : Controller
    {
        [Route("[Action]")]
        public IActionResult Index() => View();
    
        [Route("[Action]")]
        public IActionResult Other() => View();
    }
    

    以及视图中的以下链接:

    <a asp-controller="Manage/Accounts" asp-action="Index">Accounts</a>
    <a asp-controller="Manage/Account" asp-action="Other">Accounts (Other)</a>
    

    这将生成以下HTML:

    <a href="/Manage%5CAccount">Accounts</a>
    <a href="/Manage%5CAccount/Other">Accounts (Other)</a>
    

    请注意,斜杠已转义到 %5C 公平地说,这是可行的,而且这些联系实际上将我带到正确的行动上。此外,通过浏览器地址栏手动将斜杠放回还可以使我采取正确的操作。然而,这确实给了我一些丑陋的网址,我宁愿没有。

    有人能建议一种方法来阻止它从我的刀口逃走吗?

    编辑:更多详细信息

    在我努力将我的问题归结到最低限度的过程中,我担心我可能遗漏了一些关于我最终目标的重要背景。

    我正在尝试实现一个功能文件夹设置,该设置已成功地用于使用属性路由的ASP.NET MVC5和允许嵌套功能的自定义视图引擎。为了完成这项工作,我使用了 [RoutePrefix(...)] . 下面的控制器将在以下目录中 ~/Features/Manage/Accounts :

    [RoutePrefix("Manage/Accounts")]
    public class Accounts : Controller
    {
        [Route("Index")]
        public ActionResult Index() => View();
    
        [Route("Other")]
        public ActionResult Other() => View();
    }
    

    然后在如下视图中添加了链接:

    @Html.ActionLink("Accounts", "Index", "Manage/Accounts")
    @Html.ActionLink("Accounts (Other)", "Other", "Manage/Accounts")
    

    然后呈现为:

    <a href="/Manage/Accounts">Accounts</a>
    <a href="/Manage/Accounts/Other">Accounts (Other)</a>
    

    可悲的是 [路由器前缀(…)] 属性在ASP.NET核心MVC中不可用,并且使用标准 [Route(...)] 属性无法模拟MVC5中的行为。

    2 回复  |  直到 8 年前
        1
  •  1
  •   Kirk Larkin    8 年前

    您似乎混淆了控制器和路由。使用时 asp-controller ,您需要提供控制器类的名称(没有 Controller 后缀)。在您的情况下,您需要:

    <a asp-controller="Accounts" asp-action="Index">Accounts</a>
    <a asp-controller="Accounts" asp-action="Other">Accounts (Other)</a>
    

    使用上面的方法,您应该以预期的路线结束:

    <a href="/Manage/Account">Accounts</a>
    <a href="/Manage/Account/Other">Accounts (Other)</a>
    

    顺便说一句,您可以简化您的属性,比如:

    [Route("Manage/Account/[action]")]
    public class AccountsController : Controller
    {
        public IActionResult Index() => View();
    
        public IActionResult Other() => View();
    }
    

    这个 [action] 令牌可以在控制器级别应用,如图所示,避免将它添加到每个方法中。

        2
  •  1
  •   David Liang    8 年前

    柯克所说的完全正确。我只想告诉你 Area 在MVC中,因为通过查看示例中的链接,看起来您希望这些链接以 /manage .

    我以前分享过如何在MVC中建立区域。你可以看看 here 。

    推荐文章