Get UserID of the user using ASP.NET Membership

Retreiving the UserId for a user while using the ASP.NET Login controls is very simple, yet it still is one of the most frequently asked questions on the forums. Here's how to do so:

C#


    protected void Page_Load(object sender, EventArgs e)


    {


        System.Web.Security.MembershipUser mu = System.Web.Security.Membership.GetUser();


        string strUsrId = mu.ProviderUserKey.ToString();       


    }




VB.NET


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)


        Dim mu As System.Web.Security.MembershipUser = System.Web.Security.Membership.GetUser()


        Dim strUsrId As String = mu.ProviderUserKey.ToString()


    End Sub


3 comments:

  1. When I run the C# code, it gives an error:


    Object reference not set to an instance of an object.


    Which doesnt make sense..

    Its not triggering till after logging in to the site. Any ideas?

    ReplyDelete
  2. i think it should be
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

    Dim mu As System.Web.Security.MembershipUser = System.Web.Security.Membership.GetUser("user name")

    Dim strUsrId As String = mu.ProviderUserKey.ToString()

    End Sub

    ReplyDelete