glarkou
glarkou

Reputation: 7101

I want to have username as url parameter

I am new to ASP.NET MVC 3 and I want to have username/id as URL parameter using ASP.NET MVC.

For example I want to have:

http://mylink.com/username 

or

http://mylink.com/id

to redirect to my HomeController action Profile.

Is that possible?

I tried to create a new route using

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

but it is not working.

Thanks

Upvotes: 1

Views: 646

Answers (1)

danludwig
danludwig

Reputation: 47375

You should be able to accomplish the URL pattern you are after. Here is an example that should work:

Route code:

// be sure to register your custom route before the default routes
routes.MapRoute(null, // route name is not necessary
    "{username}",
    new { controller = "Home", action = "Profile", }
);

routes.MapRoute(null,
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

Controller code:

public class HomeController : Controller
{
    public ActionResult Profile(string username)
    {
        // http://mylink.com/myusername should hit this method
    }
}

Response to comment 1

I prefer not to answer loaded questions without knowing anything about your project or the URL schema you are designing. However I see a problem with it right away.You say you want to have at least 2 URL's:

By definition, this means you cannot have any users with username "About". Otherwise, the system could never know which content to deliver -- the about page, or the profile page for the username "about". In MVC, URL's are case-insensitive.

If you are creating a larger application with more pages, I would suggest you scope the URL for your Profile action. Perhaps something more like this:

With that said, you can still accomplish the URL pattern you want. But you will have to add several validations to make sure that no users have usernames matching your other routes, and you will have to write more custom routes. So you are really just making more work for yourself. You would have to do something like this in the routes:

// more specific routes must be added first

routes.MapRoute(null,
    "About",
    new { controller = "Home", action = "About", }
);

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

routes.MapRoute(null,
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

The above routes would match requests for /About to the About action, and all other /somestring requests to the Profile action.

Upvotes: 3

Related Questions