7

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 :(

Owen Blacker
  • 4,117
  • 2
  • 33
  • 70
Neo
  • 15,491
  • 59
  • 215
  • 405
  • 1
    You really shouldn't try to add fields to the MembershipUser class. If you want to store FirstName, LastName, etc, the Profile & ProfileProvider ('' in web.config) was designed for this. – danludwig Jan 06 '12 at 17:38
  • how can i use that please give me any link? – Neo Jan 06 '12 at 17:42
  • here is your link: https://www.google.com?q=asp.net+profile+provider – danludwig Jan 06 '12 at 17:49
  • You can use ProfileProvider in MVC, just as you can use MembershipProvider and RoleProvider. Profiles are ASP.NET, not WebForms. – danludwig Jan 07 '12 at 04:38

4 Answers4

5

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

Also take a look at this thread:

Community
  • 1
  • 1
Qorbani
  • 5,825
  • 2
  • 39
  • 47
1

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.
Mohamed Emad
  • 1,113
  • 1
  • 9
  • 16
0

Make a class that inherits from MembershipProvider and implement methods that are identical by just calling the SqlMembershipProvider but change others that you want a different Functionality.

Take a look at this article SQLite 3.0 Membership and Role Provider for ASP.NET 2.0

UPDATE:

The Membership system in ASP.NET was designed to create a standardized API for working with user accounts, a task faced by many web applications (refer back to Part 1 of this article series for a more in-depth look at Membership). While the Membership system encompasses core user-related properties - username, password, email address, and so on - oftentimes additional information needs to be captured for each user. Unfortunately, this additional information can differ wildly from application to application.

Rather than add additional user attributes to the Membership system, Microsoft instead created the Profile system to handle additional user properties. The Profile system allows the additional, user-specific properties to be defined in the Web.config file and is responsible for persisting these values to some data store.

Reference: Examining ASP.NET's Membership, Roles, and Profile - Part 6

Jahan Zinedine
  • 14,616
  • 5
  • 46
  • 70
0

This is how I have accomplished somthing like this. I added event onCreatedUser to CreateUserWizard and when you press CreateUser button it loads method

protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
    {
        MembershipUser mu = Membership.GetUser(CreateUserWizard1.UserName);
        int idOfInsertedUser = (int)mu.ProviderUserKey;

        TextBox tb1 = (TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("FirstName";
        string firstName= tb1.Text;
        TextBox tb2 = (TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("LastName";
        string lastName= tb2.Text;  

// now you have values of two more fields, and it is time to call your Database methods for inserting them in tables of choice...
    }
Dejan Stuparic
  • 575
  • 2
  • 13
  • 32