top*_*ool 5 asp.net asp.net-mvc asp.net-identity asp.net-core-mvc
我有 2 个控制器,名为 : AdminProfileControllerAnd UserProfileController。我想在登录后直接获取 userId 和用户角色,因为我希望用户转到AdminProfileControllerif user hasAdmin Role和转到UserProfileControllerif user has User Role。
我的代码
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
return RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError(string.Empty, "Model Erroe");
return View(model);
}
}
return View(model);
}
private IActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
if (User.IsInRole("Admin"))
{
return Redirect("/AdminProfile/Index");
}
else
{
return Redirect("/UserProfile/Index");
}
}
}
Run Code Online (Sandbox Code Playgroud)
但User.IsInRole("Admin")总是如此false,我也尝试userId通过以下代码获取:
string userId = _userManager.GetUserId(HttpContext.User);
Run Code Online (Sandbox Code Playgroud)
但它也返回 null 。登录后如何获取userId或role直接导航到指定路径?
您没有获得期望值的原因是User.IsInRole因为这会从 cookie 中读取角色,并且在您使用此方法时尚未设置 cookie。
出于同样的原因,您无法从_userManager.GetUserId(HttpContext.User). 在执行点HttpContext.User尚未设置。
在您进行检查时,要确定用户是否在角色中,最好的做法是使用UserManager.IsInRoleAsync method。此方法检查数据库中的角色。同样要获取用户对象,您可以使用UserManager.FindByNameAsync 方法并model.UserName在那里传递值。您将获得您的ApplicationObject实例,并将获得您userId的角色检查。
| 归档时间: |
|
| 查看次数: |
2319 次 |
| 最近记录: |