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




Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

3 comments:

JD said...

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?

alkhabr said...

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

Anonymous said...

Thanks a lot