How to add additional custom fields using user membership in mvc?

I redefined membership methods to create user membership.

In the account model, I overridden the CreateUser method:

 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 I need to add two more fields, for example, name and surname, but how to pass it to the above method?

As a method of overriding, CreateUser will give me an error if I add parameters like name and surname to it CreateUser

+6
source share
4 answers

You can leave the AspNetUsers table intact and create a new table to store additional information (related to the source). This way you will not violate the existing code in the membership provider.

The AspNetUsers source table contains: [Id], [E-mail], [EmailConfirmed], [PasswordHash], [SecurityStamp], [Phone Number], [PhoneNumberConfirmed], [TwoFactorEnabled], [LockoutEndDateUtc], [LockoutEnabled], [AccessFailedCount ], [username] p>

A new table for storing additional data may have, for example: [Id], [UserId] [DateOfBirth], [Biography], etc. Where [UserId] is the foreign key of the AspNetUsers table.

One of the advantages of this approach is that you can create several types of users, each of which stores the information associated with it in another table, while the general data is still in the original table.

How to do:

  • First update RegisterViewModel to contain the additional data you want.
  • Update the Register method in the account controller, here the original method is 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); } 
  • Implement the AddUserProfile method (int userId, RegisterViewModel) as you wish. You will collect additional data from the model object along with userId and save the new profile object in the database.
+1
source

You need to implement a user membership user. Here is an example implementation:

Also look at this topic:

+5
source

Create a class that inherits from MembershipProvider and implements methods that are identical, just calling SqlMembershipProvider, but changing others for which you want to use a different Functionality.

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

UPDATE:

The ASP.NET membership system was designed to create a standardized API for working with user accounts, a task that many application networks face (refer to Part 1 of this series for more in-depth membership analysis). While the membership system covers the basic user properties - username, password, email address and so on - often additional information is required for each user. Unfortunately, this additional information may differ wildly from application to application.

Instead of adding additional user attributes to the membership system, Microsoft instead created a Profile system to handle additional user properties. The Profile system allows you to use additional user-specific properties that must be defined in the Web.config file, and is responsible for storing these values ​​in some data warehouse.

Link: Exploring ASP.NET Membership, Roles, and Profile - Part 6

0
source

Here is how I did it. I added the onCreatedUser event to CreateUserWizard, and when you click the CreateUser button, it loads the 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... } 
0
source

Source: https://habr.com/ru/post/905322/


All Articles