2011-11-18 118 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]属性保护控制器和操作,或者限制访问。