Implementing Custom MembershipUser

老子叫甜甜 提交于 2019-11-28 18:57:37

This is working for me:

public class CustomMembershipUser : MembershipUser
{
    public CustomMembershipUser(
        string providerName,
        string name,
        object providerUserKey,
        string email,
        string passwordQuestion,
        string comment,
        bool isApproved,
        bool isLockedOut,
        DateTime creationDate,
        DateTime lastLoginDate,
        DateTime lastActivityDate,
        DateTime lastPasswordChangedDate,
        DateTime lastLockoutDate
        )
        : base(providerName, name, providerUserKey, email, passwordQuestion,
        comment, isApproved, isLockedOut, creationDate, lastLoginDate,
        lastActivityDate, lastPasswordChangedDate, lastLockoutDate)
    {
    }

    // Add additional properties
    public string CustomerNumber { get; set; }

}

public class CustomMembershipProvider : MembershipProvider
{

    public override MembershipUser GetUser(string username, bool userIsOnline)
    {
        if (string.IsNullOrEmpty(username))
        {
            // No user signed in
            return null;
        }

        // ...get data from db

        CustomMembershipUser user = new CustomMembershipUser(
                    "CustomMembershipProvider",
                    db.Username,
                    db.UserId,
                    db.Email,
                    "",
                    "",
                    true,
                    false,
                    db.CreatedAt,
                    DateTime.MinValue,
                    DateTime.MinValue,
                    DateTime.MinValue,
                    DateTime.MinValue);

        // Fill additional properties
        user.CustomerNumber = db.CustomerNumber;

        return user;

    }

}

// Get custom user (if allready logged in)
CustomMembershipUser user = Membership.GetUser(true) as CustomMembershipUser;

// Access custom property
user.CustomerNumber

Based on my own experience trying to do much of the same, trying to use the MembershipProvider to do this will be an ultimately frustrating and counterintuitive experience.

The idea of the membership provider model isn't to change or augment what the definition of a user is, as you're trying to do - it is to allow the Framework an alternate means of accessing the information that has already been defined as belonging to a "MembershipUser".

I think what you're really looking for is a user profile. Using ASP.NET profiles is boatloads easier than implementing your own provider. You can find the overview here.

Just so you know, I've tried to go down the MembershipProvider path before, and it's a long and windy one. You might see if just creating classes that implement IPrincipal and IIdentity will satisfy your needs, since they entail a lot less overhead.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!