小问题在很长的解释到底...MVC基于角色的路由澄清
假设属于管理员角色和属于用户角色尝试用下面的访问索引页的普通用户的管理员用户在Global.asax中注册的路由。
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] {"tst.Controllers"}
);
在HomeController中,索引操作方法使用Authorize属性装饰。
[Authorize]
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
强制匿名用户登录。
如果管理员用户使用他/她的凭据登录,我想将他/她重定向到位于管理区域中的HomeController中的索引操作方法。
如果普通用户登录,我想将他/她重定向到位于用户区域的HomeController中的索引操作方法。
我在UserAreaRegistration.cs
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"User",
"Profile/{action}",
new { area = AreaName, Controller = "Home", action = "Index" },
new { RoleConstraint = new RoleConstraint()},
new[]{ "tst.Areas.User.Controllers"}
);
}
下面的代码和用于AdminAreaRegistration.cs
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Admin",
"Profile/{action}",
new { area = AreaName, Controller = "Home", action = "Index" },
new { RoleConstraint = new RoleConstraint()},
new[]{ "tst.Areas.Admin.Controllers"}
);
}
以下代码当RoleConstraint定义如下
public class RoleConstraint: IRouteConstraint
{
public bool Match(
HttpContextBase httpContext,
Route route,
string parameterName,
RouteValueDictionary values,
RouteDirection routeDirection)
{
RoleProvider rp = new tst.Providers.CustomRoleProvider();
string[] roles = rp.GetRolesForUser(httpContext.User.Identity.Name);
if (roles != null && roles.Length > 0)
{
string roleName = roles[0];
string areaName = route.Defaults["area"].ToString();
return areaName == roleName;
}
return false;
}
}
的主Cont中AdminController中的标准LogOn操作方法滚子文件夹...
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(returnUrl)
&& returnUrl.Length > 1
&& returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//")
&& !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
问: 我是正确的思维是,当管理员/普通用户进行验证他/她必须在这行中的代码片断重定向上述
return RedirectToAction("Index", "Home");
到相应的索引操作方法(阅读:适当区域中的索引操作方法)。
如果是这样,我想知道如何。
我很困惑,因为涉及到一个常量字符串“Profile”,它不是涉及操作方法和控制器名称的通常东西。 “配置文件”既不是控制器也不是操作方法。
在登录操作的方法通过这个帖子的启发
return RedirectToAction("Index", "Home");
你可以发布什么注销返回? –