Membership.GetUser().ProviderUserKey always return

2020-04-11 05:24发布

问题:

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

回答1:

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:

    public static MembershipUser GetCurrentUser()
    {
        HttpContext httpContext = HttpContext.Current;
        if (httpContext != null && httpContext.User != null && httpContext.User.Identity.IsAuthenticated)
        {
            return Membership.GetUser();
        }

        return null;
    }

    /// <summary>
    /// Safe check of authenticity. Better than Request.IsAuthenticated in that if there's a used-to-be-valid cookie which does not correspond to the current database, it will fail safe
    /// </summary>
    /// <returns></returns>
    public static bool IsUserAuthenticated()
    {
        if (HttpContext.Current == null)
            return false;

        var request = HttpContext.Current.Request;

        if (!request.IsAuthenticated)
            return false;

        var membershipUser = GetCurrentUser();

        if (membershipUser != null)
            return true;

        return false;
    }