Igal
Igal

Reputation: 1114

Route order in ASP.Net MVC4

I'm trying to add a route without success. I have the default rout. It server urls like- http://server.com/Controller/Action (URL1) But I need also to add this url: http://server.com/BlueTheme/Controller/Action (URL2) I'm checking the parameters on the request and adding special theme for the user. I know how route config order works so below what I configured, but when using URL1, it appears that first route worked. this is strange please help.

Update Url.Action("Action","Controller") generates "BlueTheme/Controller/Action" (When I used URL1) That what made me say "it appears hat first route worked". somebody knows why it happening and what should I do?

routes.MapRoute(
    name: "Other Theme",
    url: "BlueTheme/{controller}/{action}",
    defaults: new { controller = "Home", action = "Index", HttpRoute = true }
);


routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}",
    defaults: new { controller = "Home", action = "Index", HttpRoute = true }
);

Upvotes: 0

Views: 118

Answers (1)

Rune
Rune

Reputation: 8380

The ordering of your routes look fine, but I would suppose you want

routes.MapRoute(
    name: "Other Theme",
    url: "BlueTheme/{controller}/{action}",
    defaults: new { controller = "Home", action = "Index", theme = "BlueTheme", HttpRoute = true }
);

Notice that I have added the theme route value, which the rest of your application can then access:

public ActionResult Index(string theme){ ... }

Instead of embedding "BlueTheme" in the url itself, using a constraint might be a little more elegant:

routes.MapRoute(
    name: "Other Theme",
    url: "{theme}/{controller}/{action}",
    defaults: new { controller = "Home", action = "Index", theme = "BlueTheme", HttpRoute = true },
    constraints: new { theme = "BlueTheme|BlackTheme|WhiteTheme" }
);

Upvotes: 1

Related Questions