Bern
Bern

Reputation: 7951

Combine Similar ASP.NET MVC Routes

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.

Upvotes: 1

Views: 133

Answers (1)

Stefano Altieri
Stefano Altieri

Reputation: 4628

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

Upvotes: 2

Related Questions