I've recently started using ASP.NET Forms Authentication and Membership.
I created a C# project in Visual Studio, which automatically created pages like "/Account/Login.aspx".
I then followed an example for installing aspnet_*
tables to my SQL Server database, and I've been able to use the <asp:CreateUserWizardStep>
control to create a user.
I've then been able to login as this user, and the logged in username appears when calling <asp:LoginName>
However, when I call the following in my C# code, in a Button Click Event Handler, I always get a Null Reference Exception:
string UserID = Membership.GetUser().ProviderUserKey.ToString();
Shouldn't this return the UserID
from my aspnet_users table?
If <asp:LoginName>
is showing a UserName value, shouldn't I always be able to call Membership.GetUser().ProviderUserKey
First check whether you have a valid authenticated user id. From your question, it sounds like you do have. But a series of checks is always a good practice.
I like to use these couple of methods (the second one calls the first, but you can also call the first one directly. I recommend calling the second one) which perform various checks and return a User ID or null if there is the user is not authenticated or unidentified: