bigyeti bigyeti - 2 months ago 17
ASP.NET (C#) Question

How do I get the UserId at login using asp.net Identity?

I want to get the UserId of the user successfully logging in so I can write it to a database with a timestamp for auditing purposes. This is the code fragment from the Login cs file

if (Page.IsValid)
{
// Validate the user password
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();

var result = signinManager.PasswordSignIn((this.LoginView1.FindControl("username") as TextBox).Text, (this.LoginView1.FindControl("password") as TextBox).Text, (this.LoginView1.FindControl("RememberMe") as CheckBox).Checked, shouldLockout: false);

switch (result)
{
case SignInStatus.Success:
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
break;


I tried adding

string thisuser = User.Identity.GetUserId().ToString();


and also

string thisuser = System.Web.HttpContext.Current.User.Identity.GetUserId().ToString;


before the redirect, but in each case it returns a null value. Where can I actually get the userid from if not in this Login method?

Answer

You can always find your user by name. Since the login was successful, there is no problem usint the UserName.

var userName = ((this.LoginView1.FindControl("username") as TextBox).Text;

//...

switch (result)
{
    case SignInStatus.Success:
        var loggedInUser = manager.FindByName(userName);

        //Do your log with loggedInUser!

        IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
        break;
    //...
}