使用自己的属性扩展.NET MembershipUser

时间:2011-04-29 14:57:19

标签: c# .net asp.net asp.net-membership membership

我编写了一个自定义MembershipProvider,除了一件小事之外,它非常有用,我想稍微延长MembershipUser类。

默认情况如下:

MembershipUser member = new MembershipUser(
    providerName: Membership.Provider.Name,
    name: db.userName,
    providerUserKey: null,
    email: db.userEmail,
    passwordQuestion: "",
    comment: "",
    isApproved: true,
    isLockedOut: false,
    creationDate: db.creationDate,
    lastLoginDate: db.lastLoginDate,
    lastActivityDate: db.lastActivityDate,
    lastPasswordChangedDate: DateTime.Now,
    lastLockoutDate: DateTime.Now
    );

但我想稍微扩展一下,就像这样:

MembershipUser member = new MembershipUser(
    providerName: Membership.Provider.Name,
    name: db.userName,
    guid: db.userGuid,
    company: db.companyName,
    companyGuid: db.companyGuid,
    whatever: db.whatever,
    providerUserKey: null,
    email: db.userEmail,
    passwordQuestion: "",
    comment: "",
    isApproved: true,
    isLockedOut: false,
    creationDate: db.creationDate,
    lastLoginDate: db.lastLoginDate,
    lastActivityDate: db.lastActivityDate,
    lastPasswordChangedDate: DateTime.Now,
    lastLockoutDate: DateTime.Now
    );

有没有办法扩展默认类?

3 个答案:

答案 0 :(得分:8)

当然!

只需创建一个扩展MembershipUser的类:

public class CustomUser : MembershipUser
{
    // your custom properties/methods go here
}

CustomMembershipProvider中,您可以返回CustomUser个对象。您只需将客户端应用程序转换为CustomUser即可。像这样:

var myUserObject = Membership.GetUser() as CustomUser;

答案 1 :(得分:4)

MembershipUser不是密封类,因此您可以创建一个继承自它的新类。保留现有功能,只添加您需要的额外内容。

如果您确实对其进行了扩展,则您必须编写自己的成员资格提供程序以返回新的类,或者在每次调用默认提供程序后将其从一个转换为另一个。

答案 2 :(得分:2)

  • 创建您自己的提供程序,继承自System.Web.Security.MembershipProvider
  • 创建您自己的会员资料,继承自System.Web.Security.MembershipUser
  • CreateUser()GetUser()
  • 返回您的课程