MVC role-based routing

别等时光非礼了梦想. 提交于 2019-12-17 10:32:29

问题


I have a project with 2 areas /Admin and /User.

Admin's default route is /Admin/Home/Index and user's default route is /User/Home/Index.

Is it possible to implement routing to make their home URL to look like /Profile/Index but to show content from /Admin/Home/Index for admins and /User/Home/Index for users?

upd

Finally find out how to do it

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

It works, but as for me it's not the MVC way. Does anybody knows how to do it right?


回答1:


Yes. The example you showed is very close to many of the Microsoft provided samples for using Route Constraints. The routing engine acts as a pre-proxy (or router if you will) before the request is passed into a control. Items like IRouteConstraint are defined so you can do just what you described.




回答2:


I like that solution as it's noted, but one thing to keep in mind is that routing itself shouldn't be used as the sole form of security. Just keep in mind that you should be securing your Controllers and Actions with the [Authorize] attribute, or however you're limiting access.



来源:https://stackoverflow.com/questions/8181284/mvc-role-based-routing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!