非常に長い説明の最後にある小さな質問...
管理者ロールに属する管理者ユーザーとユーザーロールに属する通常ユーザーが、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;
}
}
メインのControllersフォルダにあるAdminControllerの標準のログオンアクションメソッド...
[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」が含まれていて、アクションメソッドとコントローラー名を含む通常のものではないため、混乱しています。「プロファイル」は、コントローラーでもアクションメソッドでもありません。
この投稿に触発された MVCロールベースのルーティング