I'm relatively new to ASP.Net MVC and try to use the built-in user login functionality now. I'm able to register an user in the registration view. If I try to login with the created user this also works. I'm redirected to the master page.
But I'm not able to get the UserID of the current user. I tried my code in the HomeController and in the AccountController, but both didn't work. The statement in the first line returns always null.
var userID = User.Identity.GetUserId();
if (!string.IsNullOrEmpty(userID))
{
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(ApplicationDbContext.Create()));
var currentUser = manager.FindById(User.Identity.GetUserId());
}
Do I have to to something else before getting the UserID?
The answer is right there in your code. What does this return?
If you are using ASP.NET Identity, then after logging in (and redirecting to another page), the
IPrincipal.IIdentity
should be aClaimsIdentity
. You can try this:The above block of code is not exactly, but essentially, what the
IIdentity.GetUserId
extension method does.If none of this works, then the user may not really be logged into your site yet. After logging in, you have to redirect to another page before the server will write the authentication cookie to the browser. This cookie must be written before the
User.Identity
has all of this claims information (including theNameIdentifier
) on subsequent requests.