Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to I add more custom fields using custom membership in mvc?

I have overridden the membership methods to create a custom membership.

In the account model I've overridden the method CreateUser:

public override MembershipUser CreateUser(string username, string password,
    string email, string passwordQuestion, string passwordAnswer,
    bool isApproved, object providerUserKey, out MembershipCreateStatus status)
{
    ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(
        username, password, true);
    OnValidatingPassword(args);

    if (args.Cancel)
    {
        status = MembershipCreateStatus.InvalidPassword;
        return null;
    }

    if (RequiresUniqueEmail && GetUserNameByEmail(email) != "")
    {
        status = MembershipCreateStatus.DuplicateEmail;
        return null;
    }

    MembershipUser u = GetUser(username, false);
    if (u == null)
    {
        UserRepository _user = new UserRepository();

        // Here I call my new method which has fields I've created in the
        // User table; I'm using entity framework.    
        _user.CreateUser(username, password, email);
        status = MembershipCreateStatus.Success;
        return GetUser(username, false);
    }
    else
    {
        status = MembershipCreateStatus.DuplicateUserName;
    }

    return null;
}

public MembershipUser CreateUser(string username, string password,
    string email)
{
    using (CustomMembershipDB db = new CustomMembershipDB())
    {
        User user = new User();
        user.UserName = username;
        user.Email = email;
        user.PasswordSalt = CreateSalt();
        user.Password = CreatePasswordHash(password, user.PasswordSalt);
        user.CreatedDate = DateTime.Now;
        user.IsActivated = false;
        user.IsLockedOut = false;
        user.LastLockedOutDate = DateTime.Now;
        user.LastLoginDate = DateTime.Now;

        //Generate an email key
        // user.NewEmailKey = GenerateKey();

        db.AddToUsers(user);
        db.SaveChanges();

        //send mail
        // SendMail(user);

        return GetUser(username);
    }
}

Now here I need to add more two fields like first name and last name but how can I pass it to the above method?

As the override method CreateUser will give me an error if I add parameters like firstname and last name into it :(

like image 386
Neo Avatar asked Jan 06 '12 15:01

Neo


2 Answers

You need to implement Custom Membership User. Here is a sample implementation:

  • http://msdn.microsoft.com/en-us/library/ms366730.aspx

Also take a look at this thread:

  • Implement Custom MembershipUser and Custom MembershipProvider
  • Implementing Custom MembershipUser
like image 67
Qorbani Avatar answered Nov 16 '22 08:11

Qorbani


You can leave the AspNetUsers table intact, and create a new table to store the extra information (linked to the original one). This way you'll not break any existing code in the membership provider.

The original AspNetUsers table has: [Id],[Email],[EmailConfirmed],[PasswordHash],[SecurityStamp],[PhoneNumber],[PhoneNumberConfirmed],[TwoFactorEnabled],[LockoutEndDateUtc],[LockoutEnabled],[AccessFailedCount],[UserName]

The new table to store extra data can have for example: [Id],[UserId][DateOfBirth],[Biography], etc. Where [UserId] is the foreign key to AspNetUsers table.

One advantage of this approach, is that you can create multiple types of users, each storing its related info in a different table, while common data is still in the original table.

How to:

  1. First update the RegisterViewModel to contain the extra data you want.
  2. Update the Register method in the Account Controller, here's the original method updated with the code to insert new profile data:

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
            IdentityResult result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                // Start of new code ----------------------------------------
    
                // Get Id of newly inserted user
                int userId = user.Id; // Get Id of newly inserted user
    
                // Create a profile referencing the userId
                AddUserProfile(userId, model);
    
                // End of new code ----------------------------------------
    
                await SignInAsync(user, isPersistent: false);
                return RedirectToAction("Index", "Home");
            }
            else
            {
                AddErrors(result);
            }
        }
        return View(model);
    }
    
  3. Implement the AddUserProfile(int userId, RegisterViewModel model) method as you wish. You'll collect the extra data from the model object along with the userId and save the new profile object in the DB.
like image 1
Mohamed Emad Avatar answered Nov 16 '22 10:11

Mohamed Emad