Search code examples
c#asp.net-mvcmvcroutehandler

MVC C# custom MvcRouteHandler - How to?


Does anyone have experiences in providing a custom MvcRouteHandler? In my application I'd like to implement a globalization-pattern like http://mydomain/en/about or http://mydomain/de/about.

As for persistance, I'd like to have a cookie read as soon as a request arrives and if there is a language setting in this cookie apply it (so a user arriving at http://mydomain/ would be transferred to http://mydomain/en/ for example). If there is no cookie present, I'd like to get the first language the browser supports, apply this one and store it in this cookie.

I guess this can't be done with the standard routing mechanism mvc provides in it's initial project template. In a newsgroup I got the tip to have a look at the MvcRouteHandler and implement my own. But its hard to find a sample on how to do that.

Any ideas?


Solution

  • I don't believe a custom route handler is required for what you are doing.

    For your "globalized" URIs, a regular MVC route, with a constraint that the "locale" parameter must be equal to "en", "de", etc., will do. The constraint will prevent non-globalized URIs from matching the route.

    For a "non-globalized" URI, make a "catch-all" route which simply redirects to the default or cookie-set locale URI.

    Place the "globalized" route above the "catch-all" route in Global.asax, so that "already-globalized" URIs don't fall through to the redirection.

    You would need to make a new route handler if you want a certain URI pattern to trigger something that is not an action on a controller. But I don't think that's what you're dealing with, here.