Caline
Caline

Reputation: 175

Personalized URL for each user using ASP.NET MVC

I'd like to create a site where each user has his own home page and where the URL is in the format site\username. How can I accomplish this with ASP.NET MVC routing system?

I'm planning the follow URL layout:

mysite/ -> home page
mysite/account/register -> account register page
mysite/user1 -> user1 home page
mysite/user2 -> user2 home page

The above URL would match the following controller\action pattern:

mysite/ -> home/index
mysite/account/register -> account/register
mysite/user1 -> user/index
mysite/user2 -> user/index

How can I arrange my RegisterRoutes to solve this problem?

Upvotes: 1

Views: 726

Answers (2)

Chuck Callebs
Chuck Callebs

Reputation: 16441

Try

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

Edit: Those worrying about users maliciously (or accidentally) breaking this format by making their username as "account" or something similar should look to this link.

Upvotes: 1

Eric Petroelje
Eric Petroelje

Reputation: 60498

Rather than using a route like mysite/user1 you would probably need to use a route like mysite/users/user1. Then map it to the user/index action and have it pass the last part (user name) as a parameter to that method.

The problem with using mysite/{username} is what if someone decides to use account or something similar as their username? It would likely make their page unviewable.

Upvotes: 2

Related Questions