views:

198

answers:

3

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

I am pretty new to ASP.NET MVC.

However, based on the tutorials so far, the routing mechanism seems rather rigid.

+4  A: 

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

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

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

Careful with this route though, because it will match virtually any URL you can imagine. It should be the last route that you add to your mappings, so your other routes have a chance at the URL first.

womp
+1  A: 

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

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

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

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

Martin
+1  A: 
  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 that, then I am able to point to something like mydomain.com/userid as well as mydomain.com/home/index/1. However, if I just go to mydomain.com, it is going to the page used for userid, which makes sense, because it matches it with the first route rule and thinks the id is "", but how do i stop that behavior?