ASP.Net 核心 - 如何等待用户身份在登录后立即可用?
ASP.Net Core - How do I wait for User Identity to be available immediately after signing in?
我有一个相当标准的登录操作,但我想根据用户角色更改重定向。
但是,存在某种竞争条件:HttpContext.User
表示没有产生任何结果,导致管理员用户被重定向到错误的主页。
如何在登录后 HttpContext.User 可用之前正确 'wait'?
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginDto loginDto)
{
if (!ModelState.IsValid)
{
return View(loginDto);
}
var result = await _signInManager.PasswordSignInAsync(loginDto.Username, loginDto.Password, true, false);
if (!result.Succeeded)
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View(loginDto);
}
// This check doesn't always work because User = null
if(HttpContext.User.IsInRole(RoleEnum.Administrator.ToString())){
return LocalRedirect(Url.Action("Index", "Home", new { area = "Admin" }));
}
return LocalRedirect(loginDto.ReturnUrl ?? Url.Action("Index", "Home"));
}
在此范围内使用 UserManager 而不是 HttpContext,如下所示
var userInRole = await _userManager.IsInRoleAsync(user, role);
我有一个相当标准的登录操作,但我想根据用户角色更改重定向。
但是,存在某种竞争条件:HttpContext.User
表示没有产生任何结果,导致管理员用户被重定向到错误的主页。
如何在登录后 HttpContext.User 可用之前正确 'wait'?
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginDto loginDto)
{
if (!ModelState.IsValid)
{
return View(loginDto);
}
var result = await _signInManager.PasswordSignInAsync(loginDto.Username, loginDto.Password, true, false);
if (!result.Succeeded)
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View(loginDto);
}
// This check doesn't always work because User = null
if(HttpContext.User.IsInRole(RoleEnum.Administrator.ToString())){
return LocalRedirect(Url.Action("Index", "Home", new { area = "Admin" }));
}
return LocalRedirect(loginDto.ReturnUrl ?? Url.Action("Index", "Home"));
}
在此范围内使用 UserManager 而不是 HttpContext,如下所示
var userInRole = await _userManager.IsInRoleAsync(user, role);