User.Identity.GetUserId() returns null after successful login
Actually, the user is not signed in - not in the context of the current request (the POST /Account/Login
request), which is where User.Identity
gets its data. If you want to extract the id of the user currently trying to (and apparently succeeding) to sign in, you need to do that in some other way, like hijacking some step inside the call to SignInManager.PasswordSignInAsync
. If you are implementing your own MembershipProvider
, this should be easy.
Otherwise, you will have to wait for the next request (any request handled by some Controller's Action method should do fine) to use User.Identity
in the way you want to.
When your Login
method gets called, the request context is already evaluated and a lot of data is available. For example HTTP headers, cookies and so on. This is where all the context information is found, like User.Identity
.
When you call SignInManager.PasswordSignInAsync(...)
, this does not affect the values of the request context, because this would make no sense – since the browser has not changed its mind about what it sent a few milliseconds ago. What it does affect is the response context to add a cookie containing some user and session id. This cookie is then sent to the browser, which then sends it back to server for each successive request. So all requests later than this one (until the user signs out or the cookie gets too old) will include information for the User.Identity
to interpret.
User.Identity.GetUserId() returns null in cotrollers constructor
Retrieve current logged in user UserID
using Microsoft.AspNet.Identity;
In controller constructor use this:
System.Web.HttpContext.Current.User.Identity.GetUserId();
Instead of this is used in controller Action Method:
var userId = User.getUserId();
Because in constructor you can't get the current User.Identity by default you need to specify it explicitly.
User.Identity.GetUserId() always returns null in controller action
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.
ASP.NET MVC - Login Success, but userId returns null
After logging in (and redirecting to another page), the IPrincipal.IIdentity
should be a ClaimsIdentity
. You can try this:
var claimsIdentity = User.Identity as ClaimsIdentity;
if (claimsIdentity != null)
{
// the principal identity is a claims identity.
// now we need to find the NameIdentifier claim
var userIdClaim = claimsIdentity.Claims
.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier);
if (userIdClaim != null)
{
var userIdValue = userIdClaim.Value;
}
}
This should work for you. If you still unable to get the id then you have to redirect to another page before the server will write the authentication cookie to the browser.
Or Another approach is this :
switch (result)
{
case SignInStatus.Success:
ApplicationUser user = UserManager.FindByName(model.UserName);
string UserId = user.Id;
returnUrl = CheckUserRoleAndRedirect();
return RedirectToLocal(returnUrl);
}
ASP.NET Identity user null after login
The issue is that User.Identity
is unavailable until after you redirect. An easy way around this is to use the username rather than id to get the correct ApplicationUser
.
var manager = new UserManager<ApplicationUser>(store);
var user = manager.FindByName(model.UserName);
GenerateUserCookie(user);
Related Topics
How to Add/Update Child Entities When Updating a Parent Entity in Ef
How to Loop Through All Fields in an Object in C#
How to Trim All Elements in a List
Drawing a Triangle With Rounded Corners
Generate C# Class from SQL Server Table Without Store Procedure
Generate Xml for <Govtalkmessage Xmlns="Http://Www.Govtalk.Gov.Uk/Cm/Envelope">
Ziparchive Gives Unexpected End of Data Corrupted Error
Reportviewer: Show Reports in Print Layout With Page Width Zoommode
Find Item in Observablecollection Without Using a Loop
File and Line Numbers for Errors Are Not Displaying in the Error List Unless the File Is Open
The Find Element Returns Empty String..Using Xpath Contains,Text()
Storing Enums as Strings in Mongodb
User.Identity.Getuserid() Returns Null After Successful Login
Using Selenium2, How to Check If Certain Text Exists on the Page
How to Add Double Quotes to a String That Is Inside a Variable
Mongodb C# Exception Cannot Deserialize String from Bsontype Int32
Linq - Groupby a Key and Then Put Each Grouped Item into Separate 'Buckets'