【问题标题】:MVC role-based routingMVC 基于角色的路由
【发布时间】:2012-01-01 03:35:56
【问题描述】:

我有一个包含 2 个区域 /Admin 和 /User 的项目。

管理员默认路由是/Admin/Home/Index,用户默认路由是/User/Home/Index

是否可以实施路由以使其主页 URL 看起来像 /Profile/Index 但为管理员和 /Admin/Home/Index 显示内容strong>/User/Home/Index 对于用户?

更新

终于知道怎么做了

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 方式。有人知道怎么做吗?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 authorization url-routing


    【解决方案1】:

    是的。您展示的示例与 Microsoft 提供的许多使用 Route Constraints 的示例非常接近。在将请求传递到控件之前,路由引擎充当预代理(或路由器,如果您愿意的话)。定义了 IRouteConstraint 之类的项目,因此您可以按照您的描述进行操作。

    【讨论】:

      【解决方案2】:

      我喜欢上面提到的那个解决方案,但要记住的一件事是路由本身不应该用作唯一的安全形式。请记住,您应该使用 [Authorize] 属性保护您的控制器和操作,否则您将限制访问。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-06-12
        • 1970-01-01
        • 2015-07-17
        • 1970-01-01
        • 2021-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多