MVC role-based routing

2019-01-10 19:28发布

问题:

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.