views:

49

answers:

2

Is there a way to create a route like this "http://mysite/Username" ?

A: 
routes.MapRoute(
    "RouteName",
    "{username}",
    new { controller = "SomeController", action = "SomeAction", username = "" }
);

public class SomeController : Controller
{
    public ActionResult SomeAction(string username)
    { ... }
}
Serhat Özgel
+6  A: 

Yes. Create a route that matches a user using a routing constraint:

routes.MapRoute(
            "User",                                 // Route name
            "{user}",                           // URL with parameters
            new { controller = "User", action = "Index", user = "" },  // Parameter defaults
            new { isUser = new MustBeUserConstraint() }
        );

public class MustBeUserConstraint : IRouteConstraint
{
    public bool Match
        (
            HttpContextBase httpContext, 
            Route route, 
            string parameterName, 
            RouteValueDictionary values, 
            RouteDirection routeDirection
        )
    {
        ...ensure that there is a user route value and validate that it is a user...
    }

}
tvanfosson