我怎么能用asp.net mvc路由做到这一点?

时间:2010-03-01 12:37:58

标签: asp.net-mvc routing

有没有办法创建这样的路线“http://mysite/Username”?

2 个答案:

答案 0 :(得分:6)

是。使用路由约束创建匹配用户的路由:

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...
    }

}

答案 1 :(得分:0)

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

public class SomeController : Controller
{
    public ActionResult SomeAction(string username)
    { ... }
}