I'm using ASP.NET Core Identity to do the authentication on my website and I'm trying to log user id to the DB as soon as they login but I don't seem to be able to access them using the following code. The GetResult()
returns null here but it works fine if it's on the next page, but just not in the OnPostAsync
method where it needs to be.
Input.UserIDOrLogonName
does not contain the user id.
private readonly SignInManager<User> _signInManager;
private readonly UserManager<User> _userManager;
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
if (ModelState.IsValid)
{
var result = await _signInManager.PasswordSignInAsync(Input.UserIDOrLogonName, Input.Password, Input.RememberMe, lockoutOnFailure: true);
if (result.Succeeded)
{
var userId = _userManager.GetUserAsync(HttpContext.User)
.GetAwaiter().GetResult().UserId;
_audit.RecordAction(AuditType.LoginSuccess, userId);
return LocalRedirect(returnUrl);
}
Is there any other way to get to the instance of the User?
For HttpContext.User
, it will work for sub-request after loging.
If you want to log UserId, try to find the user by email like
if (result.Succeeded)
{
var user = await _userManager.FindByEmailAsync(Input.Email);
var userId = user.Id;
_logger.LogInformation("User logged in.");
return LocalRedirect(returnUrl);
}