tag-helpers未正确生成我的网址

时间:2016-10-27 15:46:11

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

我设置了以下路线

    app.UseMvc(routes =>
    {

        routes.MapRoute(
            name: "admin",
            template: "{controller=Home}/{action=Index}/{id?}",
            defaults: new {Area = "Admin"},
            constraints: new {HostConstraint = new MyConstraint()});
        routes.MapRoute(
            name: "admin-rep",
            template: "Rep/{controller=Home}/{action=Index}/{id?}",
            defaults: new { Area = "" },
            constraints: new { HostConstraint = new MyConstraint() });

        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });

在这种情况下,MyConstraint始终返回 true

  • 如果我尝试访问路径“/”,我最终会进入区域管理员,控制器主页,操作索引。没关系。
  • 如果我尝试访问“/ rep”,那么我最终会进入根区域,控制器主页,动作索引。好 。问题是该视图有一个链接引用我的HomeController中的另一个动作(来自根区域)。我期待链接指向/ rep / home / action2,但生成的路由是/ home / action2。这就像生成网址时有一些错误的匹配?
<a asp-action="Action">Action</a>

@Html.ActionLink("Action", "Action")

2 个答案:

答案 0 :(得分:3)

重新排序您的路线,先写admin-rep然后再写admin

app.UseMvc(routes =>
{


    routes.MapRoute(
        name: "admin-rep",
        template: "Rep/{controller=Home}/{action=Index}/{id?}",
        defaults: new { Area = "" },
        constraints: new { HostConstraint = new MyConstraint() });

    routes.MapRoute(
        name: "admin",
        template: "{controller=Home}/{action=Index}/{id?}",
        defaults: new {Area = "Admin"},
        constraints: new {HostConstraint = new MyConstraint()});

    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});

答案 1 :(得分:1)

您使用了Area,但我认为您没有在标记帮助器中指定asp-area属性,这会导致此问题。有关设置asp-area的更多信息,请参阅以下链接:

Asp.Net MVC Core 1.0 - anchor tag helper with an empty area