MVC 基于角色的路由 [英] MVC role-based routing
问题描述
我有一个包含 2 个区域/Admin 和/User 的项目.
I have a project with 2 areas /Admin and /User.
管理员的默认路由是/Admin/Home/Index,用户的默认路由是/User/Home/Index.
Admin's default route is /Admin/Home/Index and user's default route is /User/Home/Index.
是否可以实现路由,使他们的主页 URL 看起来像 /Profile/Index,但向管理员和 /Admin/Home/Index 显示内容strong>/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?
更新
终于知道怎么做了
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 方式.有人知道怎么做吗?
It works, but as for me it's not the MVC way. Does anybody knows how to do it right?
推荐答案
是的.您展示的示例与 Microsoft 提供的许多使用路由约束的示例非常接近.在请求传递到控件之前,路由引擎充当预代理(或路由器,如果您愿意).像 IRouteConstraint 这样的项目被定义,所以你可以按照你描述的做.
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.
这篇关于MVC 基于角色的路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!