Antony Brahin Antony Brahin -3 years ago 156
ASP.NET (C#) Question

User.Identity.GetUserId() always returns null in controller action

I needed to use current logged in user id in controller. It always returns null. I am already logged in. Here's my code.

if (string.IsNullOrEmpty(userId)) userId = User.Identity.GetUserId();


I tried adding the reference

using Microsoft.AspNet.Identity;


I also tried adding a claim

public const string UserId = "http://schemas.xmlsoap.org/ws/2014/03/mystuff/claims/UserId";
userIdentity.AddClaim(new Claim(CustomClaimTypes.UserId, Id));


When I try to retrieve the claim, it gives null as well.

(identity as ClaimsIdentity).FirstOrNull(CustomClaimTypes.UserId);


Any help would be appreciated.

Additional Info requested in comments:

It's the normal login provided by aspnetuser.

var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.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:
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}


Request.IsAuthenticated returns true.

Claims added here.

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
userIdentity.AddClaim(new Claim(CustomClaimTypes.UserId, Id));

return userIdentity;
}


Cookies

Answer Source

Here is the answer, I managed to get it work.

I just moved the User.Identity.GetUserId(); to a helper class method.

I just want to reiterate, the request is not the login request. Its a separate request after the login.

Thank you guys for your time.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download