Asp.net mvc url routing

How do I match something like domain.com/username? The problem is that I believe MVC routing is looking for a controller to determine how it should handle the mapping request.

I am new to ASP.NET MVC.

However, based on the tutorials, the routing mechanism seems pretty rigid.

+2


source to share


3 answers


It's actually quite flexible, I think you will find it powerful enough with some experience. Here you can do what you want:

routes.MapRoute("MyRoute", 
                 "{username}", 
                 new { controller = "Home", action = "Index", username = "" });

      



This selects the default controller ("Home") and the default action method ("Index") and passes it the username parameter (which is set to "" by default).

Be careful with this path because it will match just about any URL you can imagine. This should be the last route you add to your mappings, so your other routes have a chance in the url first.

+6


source


To add to the womp - I would go this route (pun intended):

routes.MapRoute("MyRoute", 
                 "user/{username}", 
                 new { controller = "User", action = "Index", username = "" });

      



This will display urls: domain.com/user/ {username}

And you can always change the controller and action to whatever you want.

+1


source


  routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute("MyRoute",
              "{id}",
              new { controller = "Home", action = "User", id = "" });


            routes.MapRoute(
              "Default",                                              // Route name
              "{controller}/{action}/{id}",                           // URL with parameters
              new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
          );

      

If I have something like this, I can point to something like mydomain.com/userid as well as mydomain.com/home/index/1. However, if I just go to mydomain.com it goes to the page used for the userid, which makes sense because it matches it with the first route rule and thinks the id is "", but how can I stop this behavior?

+1


source







All Articles