Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC catch-all routing

I have read a few threads on StackOverflow about this, but cannot get it to work. I have this at the end of my RegisterRoutes in Global.asax.

routes.MapRoute(
            "Profile",
            "{*url}",
            new { controller = "Profile", action = "Index" }
            );

Basically what I'm trying to achieve is to have mydomain.com/Username point to my member profilepage. How would I have to set up my controller and RegisterRoutes in order for this to work?

Currently mydomain.com/somethingthatisnotacontrollername gets a 404-error.

like image 610
David W. Avatar asked Jul 27 '11 01:07

David W.


1 Answers

Solution that works for your case but is not recommended

You have a predefined set of controllers (usually less than 10) in your application so you can put a constraint on controller name and then route everything else to user profile:

routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    new { controller = "Home|Admin|Reports|..." }
);
routes.MapRoute(
    "Profile",
    "{username}/{action}",
    new { controller = "Profile", action = "Details" }
);

But this will not work in case some username is the same as your controller name. It's a small possibility based on experience end empirical data, but it's not 0% chance. When username is the same as some controller it automatically means it will get handled by the first route because constraints won't fail it.

Recommended solution

The best way would be to rather have URL requests as:

www.mydomain.com/profile/username

Why do I recommend it to be this way? Becasue this will make it much simpler and cleaner and will allow to have several different profile pages:

  • details www.mydomain.com/profile/username
  • settings www.mydomain.com/profile/username/settings
  • messages www.mydomain.com/profile/username/messages
  • etc.

Route definition in this case would be like this:

routes.MapRoute(
    "Profile",
    "Profile/{username}/{action}",
    new { controller = "Profile", action = "Details" }
);
routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
like image 68
Robert Koritnik Avatar answered Sep 20 '22 11:09

Robert Koritnik