5
votes

I have the following routes set up

    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 in this case always return true.

  • If I try to access the route "/" I end up in the area Admin , controller Home, action Index. It is OK.
  • If I try to access "/rep" then i end up in the root area, controller home, action index . OK . The problem is then that this view has a link referencing another action in my HomeController (from the root area). I was expecting the link to point to /rep/home/action2 but the generated route is /home/action2 instead. It is like there is some wrong matching when generating the urls ??
<a asp-action="Action">Action</a>

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

2 Answers

4
votes

reorder your routes, write admin-rep first and then 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
votes

You used Area but I think you didn't specify asp-area attribute in tag helper and it cause to this problem. For more informatin to set asp-area see link below:

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