Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC URL Routes

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.

like image 674
Oundless Avatar asked Jul 22 '09 13:07

Oundless


People also ask

What is URL routing in MVC?

In MVC, routing is a process of mapping the browser request to the controller action and return response back. Each MVC application has default routing for the default HomeController. We can set custom routing for newly created controller.

How you can define a route in ASP.NET MVC?

Routing in ASP.NET MVC cs file in App_Start Folder, You can define Routes in that file, By default route is: Home controller - Index Method. routes. MapRoute has attributes like name, url and defaults like controller name, action and id (optional).

Where are routes registered in ASP.NET MVC application?

Every MVC application must configure (register) at least one route configured by the MVC framework by default. You can register a route in RouteConfig class, which is in RouteConfig. cs under App_Start folder.

How are URL patterns mapped to a handler in ASP.NET MVC?

URL patterns for routes in MVC Applications typically include {controller} and {action} placeholders. When a request is received, it is routed to the UrlRoutingModule object and then to the MvcHandler HTTP handler.


1 Answers

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.

like image 147
George Stocker Avatar answered Oct 04 '22 22:10

George Stocker