Get current user id in ASP.NET Identity 2.0

前端 未结 4 1367
余生分开走
余生分开走 2020-12-13 05:48

I just switched over to using the new 2.0 version of the Identity Framework. In 1.0 I could get a user object by using manager.FindByIdAsync(User.Identity.GetUserId()

相关标签:
4条回答
  • 2020-12-13 05:56

    I had the same issue. I am currently using Asp.net Core 2.2. I solved this problem with the following piece of code.

    using Microsoft.AspNetCore.Identity;
    var user = await _userManager.FindByEmailAsync(User.Identity.Name);
    

    I hope this will be useful to someone.

    0 讨论(0)
  • 2020-12-13 06:03

    GetUserId() is an extension method on IIdentity and it is in Microsoft.AspNet.Identity.IdentityExtensions. Make sure you have added the namespace with using Microsoft.AspNet.Identity;.

    0 讨论(0)
  • 2020-12-13 06:17

    Just in case you are like me and the Id Field of the User Entity is an Int or something else other than a string,

    using Microsoft.AspNet.Identity;
    
    int userId = User.Identity.GetUserId<int>();
    

    will do the trick

    0 讨论(0)
  • 2020-12-13 06:18

    In order to get CurrentUserId in Asp.net Identity 2.0, at first import Microsoft.AspNet.Identity:

    C#:

    using Microsoft.AspNet.Identity;
    

    VB.NET:

    Imports Microsoft.AspNet.Identity
    


    And then call User.Identity.GetUserId() everywhere you want:

    strCurrentUserId = User.Identity.GetUserId()
    

    This method returns current user id as defined datatype for userid in database (the default is String).

    0 讨论(0)
提交回复
热议问题