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.
Yes, if you use constraints:
like so:
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 yourstringroute 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.