Search code examples
asp.net-mvcasp.net-identityidentity

Log user information after successful login


In Identity core, I am trying to log the user information after successful login but I am just getting empty UserName in the LogSignIn action.

In this method I am calling LogSignIn action by sending HttpContextBase type object and notify enum to get the success or error message.

Action Login

public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    if (!ModelState.IsValid)
    {
       return View(model);
    }
    var result = await SignInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, shouldLockout: false);
    switch (result)
    {
        case SignInStatus.Success:
            {
                SignInLogger.LogSignIn(HttpContext, Notify.Success);
                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:
                SignInLogger.LogSignIn(HttpContext, Notify.Error);
                ModelState.AddModelError("", "Invalid login attempt.");
                return View(model);
      }
}

In this method I am trying to log the user information to the DB but Idenity don't have the value in the Name. SignIn Logger

public static void LogSignIn(HttpContextBase httpcontext, Notify notifymessage)
{
    using (var context = new WorkshopEntities())
    {
        MessageLog log = new MessageLog();
        log.Date = DateTime.Now;
        log.Type = (int)MessageLogType.Information;
        log.Message = "Logged In";
        log.CustomMessage = notifymessage.ToString();
        log.UserEmail = httpcontext.User.Identity.Name ?? "N/A";
        log.Address= HttpContext.Current.Request.UserHostAddress;
        context.MessageLogs.Add(log);

        try
        {
            context.SaveChanges();
        }
        catch (Exception ex)
        {
            ErrorLogger.LogError(ex);
        }
    }
}

So, far what I understand that PasswordSignInAsync task didn't complete and I am trying to fetch the information that is still not available.

I don't know it is a best approach or not but I am trying to log the user information at the time of user try to login.


Solution

  • Since the user has successfully logged in, you could retrieve the Username from the model itself.

    Other user information can be obtained as such:

    var userName = model.Username;
    ApplicationUser user = UserManager.FindByName(userName);
    string userid = user.UserId.ToString();
    //Email
    //Other properties...