if (ModelState.IsValid)
{
var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
_logger.LogInformation("User logged in.");
if (User.IsInRole("User"))
{
return RedirectToAction("Index", "Home");
}
if (User.IsInRole("Admin"))
{
return RedirectToAction("Index", "Admin");
}
if (User.IsInRole("Administrator"))
{
return RedirectToAction("Index", "Administrator");
}
}
}
我希望用户(如管理员)在登录后立即重定向到他的页面,并将用户重定向到他的页面。
解决方案
if (ModelState.IsValid)
{
var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);
var user = await _userManager.FindByEmailAsync(Input.Email);
var roles = await _userManager.GetRolesAsync(user);
if (result.Succeeded)
{
_logger.LogInformation("User logged in.");
if (roles.Contains("User")) { return RedirectToAction("Index", "Home"); }
if (roles.Contains("Admin")) { return RedirectToAction("Index", "Admin"); }
if (roles.Contains("Administrator")) { return RedirectToAction("Index", "Administrator"); }
}
if (result.RequiresTwoFactor)
{
return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning("User account locked out.");
return RedirectToPage("./Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return Page();
}
}