Extending the .NET MembershipUser with own properties
Asked Answered
D

3

9

I've written a custom MembershipProvider that works really great except one little thing, I'd like to extend the MembershipUser class a bit.

The default looks like this:

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
    );

But I'd like to extend it a bit, something like this:

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
    );

Is there a way to extend the default class?

Dingo answered 29/4, 2011 at 14:57 Comment(0)
G
8

Of course!

Just create a class that extends MembershipUser:

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

In your CustomMembershipProvider you can return your CustomUser object. You just have to cast in the client application to CustomUser. Like so:

var myUserObject = Membership.GetUser() as CustomUser;
Glabrous answered 29/4, 2011 at 15:3 Comment(0)
S
4

MembershipUser isn't a sealed class, so you can just create a new class that inherits from it. Keep the existing functionality and only add the extra stuff you need.

If you do extend it, you'll either have to write your own membership provider that returns your new class, or convert from one to the other after each call into the default providers.

Surfperch answered 29/4, 2011 at 15:3 Comment(0)
I
2
  • Create your own provider, inherit from System.Web.Security.MembershipProvider
  • Create your own membership info, inherit from System.Web.Security.MembershipUser
  • Return your class from CreateUser(), GetUser(), etc
Indira answered 29/4, 2011 at 20:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.