1

I have two very similar ASP.NET MVC routes, provided below.

Is there anyway to combine the two routes and place a conditional statement so that (1) any requests to "logs/email/" goes to the EmailLogsController, and requests to "logs/user/" goes to the UserLogsController?

// URL: /areax/logs/email/
// URL: /areax/logs/email/details/51
// URL: /areax/logs/email/details/117
context.MapRouteLowercase(
    "AreaX.Log.Email",
    "areax/logs/email/{action}/{id}",
    new
    {
        controller = "EmailLogs",
        action = "Index",
        id = UrlParameter.Optional
    },
    new[] { ControllerNamespaces.AreaX }
);

// URL: /areax/logs/user/
// URL: /areax/logs/user/details/1
// URL: /areax/logs/user/details/10
context.MapRouteLowercase(
    "AreaX.Log.User",
    "areax/logs/user/{action}/{id}",
    new
    {
        controller = "UserLogs",
        action = "Index",
        id = UrlParameter.Optional
    },
    new[] { ControllerNamespaces.AreaX }
);

As it stands they don't look very DRY.

DaveRandom
  • 87,921
  • 11
  • 154
  • 174
Bern
  • 7,808
  • 5
  • 37
  • 47

1 Answers1

2

If you can rename your controller (removing the Log suffix) you can try using the {controller} keyword:

    context.MapRouteLowercase(
    "AreaX.Log.Email",
    "areax/logs/{controller}/{action}/{id}",
    new
    {
        action = "Index",
        id = UrlParameter.Optional
    },
    new[] { ControllerNamespaces.AreaX }
);
Stefano Altieri
  • 4,550
  • 1
  • 24
  • 41
  • serry.. doesn't compile... givi me a minute – Stefano Altieri Feb 25 '13 at 10:54
  • See http://stackoverflow.com/questions/3303801/how-to-achieve-a-dynamic-controller-and-action-method-in-asp-net-mvc – Stefano Altieri Feb 25 '13 at 10:58
  • That was in my original solution but the requirement to name the URL like this: /areax/logs/user/details/10 as opposed to this: /areax/logs/userlogs/details/10 (note the repeated "logs") means this answer isn't quite right. Thanks for the suggestion though. – Bern Feb 25 '13 at 11:22
  • 1
    @Bern as suggested by Stefano, remove the "Logs" suffix and you should be fine. – tucaz Feb 25 '13 at 11:43
  • I appreciate your efforts but what you're suggesting is that I change my URL naming requirement to accommodate a suggested solution. If there is now way to address the requirement using MVC routing techniques then that's the answer I'll settle for. And even if I remove the "Logs" suffix that raises other issues, i.e. "UserLogsController" becomes "UserController" which isn't actually correct. – Bern Feb 25 '13 at 11:58