我使用该身份为用户分配角色。现在我想根据用户的角色将用户重定向到某些页面。例如,具有角色的用户" user"登录后重定向到一个页面说"你好用户"。不同于管理员等等。我已经创建了每个页面并验证了授权。但是我应该在登录后重定向到哪里?
答案 0 :(得分:0)
您只需更改登录发布操作即可检查用户并重定向到正确的视图。
为普通用户创建单独的视图。
NormalUser.cshtml
@{
ViewBag.Title = "Normal User";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Hello User!</h2>
控制器内部
[Authorize(Roles = "user")]
public ActionResult NormalUser()
{
ViewBag.Message = "Hello normal user.";
return View();
}
然后登录发布操作
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, change to shouldLockout: true
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
var user = await UserManager.FindByEmailAsync(model.Email);
var userRole = await UserManager.GetRolesAsync(user.Id);
if (userRole.Any(role => role == "user"))
{
RedirectToAction("NormalUser", "Home");
}
else
{
RedirectToAction("Index", "Home");
}
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
}
检查此github项目以获取代码。