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

4

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

Winters answered 6/1, 2012 at 15:31 Comment(4)
You really shouldn't try to add fields to the MembershipUser class. If you want to store FirstName, LastName, etc, the Profile & ProfileProvider ('<profile>' in web.config) was designed for this.Eyebright
how can i use that please give me any link?Winters
here is your link: google.com?q=asp.net+profile+providerEyebright
You can use ProfileProvider in MVC, just as you can use MembershipProvider and RoleProvider. Profiles are ASP.NET, not WebForms.Eyebright
D
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.
Deictic answered 28/8, 2014 at 12:13 Comment(0)
E
5

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

Also take a look at this thread:

Ealdorman answered 6/1, 2012 at 15:37 Comment(1)
can you suggest me where i can put my firstname prop in above code?Winters
D
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.
Deictic answered 28/8, 2014 at 12:13 Comment(0)
I
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

Insignia answered 6/1, 2012 at 15:37 Comment(3)
can you suggest me where i can put my firstname prop in above code?Winters
@ashuthinks If you read that article it shows you the easier way to extend functionaries of ASP.NET Membership.Insignia
But If you want to go with this code you should update the user row after created by Membership Provider outside of this method.Insignia
N
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...
    }
Nernst answered 7/2, 2012 at 23:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.