2011-11-18 123 views
17

我有一個包含2個區域/ Admin和/ User的項目。MVC基於角色的路由

管理員的默認路由是/管理/首頁/指數和用戶的默認路由是/用戶/主頁/指數

是否有可能實現路由功能,以使他們的家庭URL看起來像/資料/指數而是要說明從內容/管理/主頁管理員/指標,爲用戶/用戶/主頁/指數

UPD

最後找出如何做到這一點

context.MapRoute(
    "Admin", 
    "Profile/{action}", 
    new { area = AreaName, controller = "Home", action = "Index" }, 
    new { RoleConstraint = new Core.RoleConstraint() }, 
    new[] { "MvcApplication1.Areas.Admin.Controllers" } 
); 
... 
context.MapRoute(
    "User", 
    "Profile/{action}", 
    new { area = AreaName, controller = "Home", action = "Index" }, 
    new { RoleConstraint = new Core.RoleConstraint() }, 
    new[] { "MvcApplication1.Areas.User.Controllers" } 
); 

public class RoleConstraint : IRouteConstraint 
{ 
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) 
    { 
     string roleName = db.GetRoleByUserName(httpContext.User.Identity.Name); 
     string areaName = route.Defaults["area"].ToString(); 
     return areaName == roleName; 
    } 
} 

它的工作原理,但對我來說這不是MVC方式。有誰知道如何做對嗎?

回答

4

是的。您展示的示例非常接近許多Microsoft提供的使用路由約束的示例。在請求傳入控件之前,路由引擎充當預代理(或者路由器,如果您願意的話)。像IRouteConstraint這樣的項目被定義,所以你可以做你剛剛描述的內容。

3

我喜歡這個解決方案,但需要注意的一點是,路由本身不應該被用作唯一的安全形式。請記住,您應該使用[Authorize]屬性保護控制器和操作,或者限制訪問。