ASP.NET MVC 2 - do UrlParameter.Optional records should be at the end of the route?

I am moving the site from ASP.NET MVC 1 to ASP.NET MVC 2. Currently the site supports the following routes:

/{country}/{language}/{controller}/{action} /{country}/{controller}/{action} /{language}/{controller}/{action} /{controller}/{action} 

The formats for country and language differ by Regex and have suitable limitations. In MVC 1, I registered each of them as a separate route - for each of about 20 combinations. In MVC 2, I try to get the same thing that works with a single route to cover all four cases using UrlParameter.Optional , but I can't get it to work - if I define country and language as both optional, then the route /Home/Index , for example, does not match the route. This is what I am trying to do:

 routes.MapRoute("Default", "{country}/{language}/{controller}/{action}", new { country = UrlParameter.Optional, language = UrlParameter.Optional, controller = "Home", action = "Index" }, new { country = COUNTRY_REGEX, language = LANGUAGE_REGEX }); 

Is it simply not possible because my options are at the beginning of the route, or did I just miss something? I cannot find any documentation to tell me what I am doing is impossible or to point me in the right direction.

+7
asp.net-mvc asp.net-mvc-routing
source share
1 answer

Hm. Interesting.

Here is the best I could come up with. I guess this is a bad idea, but this is the only workaround I could think of. I would be interested to hear some suggestions / problems / complaints.

You can map the nearsighted route as follows:

 routes.MapRoute( "Localized", "{*loc}", new { controller = "Localizer", action = "RedirectIt" }, new { loc = REGEX_CONSTRAINT_FOR_ENTIRE_ROUTE_VALUE } ); 

Then in your Localizer controller you can redirect to the correct action, but you want:

 public class LocalizerController : Controller { public ActionResult RedirectIt(string loc) { //split up the loc string //and determine the correct redirect path for the request } } 

I am a man of cheap tricks. What can I say?

+2
source share

All Articles