MVC基于角色的路由 [英] MVC role-based routing
问题描述
我有2个区/ Admin和/用户的项目。
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.
是否有可能实现路由功能,以使他们的家庭URL看起来像 /资料/指数但是从表现内容的 /管理/首页/索引作为管理员和< STRONG> /用户/主页/索引作为用户?
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;
}
}
它的工作原理,但对我来说这不是MVC的方式。有谁知道怎么做是正确的?
It works, but as for me it's not the MVC way. Does anybody knows how to do it right?
推荐答案
是的。这个例子你应该是非常接近的许多微软使用路由约束提供样品。路由引擎充当pre-代理(或路由器,如果你愿意)之前,请求被传递到控制。像IRouteConstraint项目的定义,因此您可以您所描述正是这样做。
Yes. That example you should 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屋!