2015-04-21 71 views

回答

2

我希望我已經正確理解你的問題 - 我很抱歉,如果我沒有。

創建自定義RouteConstraint

在我的例子,我檢查登錄用戶的用戶名的URL匹配。如果用戶名匹配,則路由有效,並且將調用主控制器上的索引操作。

如果用戶名是heymega ..

http://localhost:48735/heymega/將是有效的

http://localhost:48735/chris/將是無效的

public class UserNameRoute : IRouteConstraint 
{ 
    public bool Match(System.Web.HttpContextBase httpContext, System.Web.Routing.Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) 
    { 

     //Get the username from the URL 
     var username = values["username"].ToString(); 

     if (httpContext.User.Identity.IsAuthenticated) 
     { 
      //Compare the username to the logged in user 
      return httpContext.User.Identity.Name == username; 

     } 

     return false; 
    } 
} 

定義你的路線,這將支持該限制

 routes.MapRoute(
      name: "UserNameRoute", 
      url: "{username}", 
      defaults: new { controller = "Home", action = "Index" }, 
      constraints: new { username = new UserNameRoute() } 
     );