Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 2 - do UrlParameter.Optional entries have to be at the end of the route?

I am migrating a site from ASP.NET MVC 1 to ASP.NET MVC 2. At the moment, the site supports the following routes:

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

The formats for country and language are distinguishable by Regex and have suitable constraints. In MVC 1, I registered each of these as a separate route - for each of around 20 combinations. In MVC 2, I have been trying to get the same thing working with one route to cover all four cases, using UrlParameter.Optional, but I can't seem to get it working - if I define country and language as both optional, then the route /Home/Index for example doesn't successfully 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 this just impossible because my optionals are at the beginning of the route, or am I just missing something? I can't find any documentation to either tell me what I am doing is impossible or to point me in the right direction.

like image 205
David M Avatar asked Jun 10 '10 13:06

David M


1 Answers

Hmm. Interesting.

Here's the best I could come up with. I'm guessing that this is a bad idea, but it's the only workaround I could think of. I'd be interested to hear some suggestions/concerns/complaints.

You could map a myopic route like this:

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 however you'd like:

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

I'm a man of cheap tricks. What can I say?

like image 161
Evan Nagle Avatar answered Oct 22 '22 06:10

Evan Nagle