2

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.

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1
  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?

1 Comment

the order of the routes is the order they are checked upon. So the least important should come last. Thats the one called MyRoute. Move it below Default route.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.