views:

221

answers:

1

In ASP.NET MVC, is it possible to define routes that can determine which controller to use based on the data type of part of the URL?

For example:

routes.MapRoute("Integer", "{myInteger}", new { controller = "Integer", action = "ProcessInteger", myInteger = "" });

routes.MapRoute("String", "{myString}", new { controller = "String", action = "ProcessString", myString = "" });

Essentially, I want the following URLs to be handled by different controllers even though they have the same number of parts:

mydomain/123

mydomain/ABC

P.S. The above code doesn't work but it's indicative of what I want to acheive.

+6  A: 

Yes, if you use constraints:

like so:

 routes.MapRoute(
                "Integers",
                "{myInteger}",
                    new { controller = "Integer", action = "ProcessInteger"},
                    new { myInteger = @"\d+" }
          );

If you put that route above your string route (that doesn't contain the constraint for @"\d+"), then it'll filter out any routes containing integers, and anything that doesn't have integers will be passed through and your string route will pick it up.

The real trick is that Routes can filter what's coming through based on Regular Expressions, and that's how you can determine what should pick it up.

George Stocker
That works a treat, thanks.
Moose Factory
No problem. I've had *plenty* of issues with ASP.NET MVC routes. Enough to fill a book. Or a few blog posts. If I can ever get a chance to finish them.
George Stocker