Search code examples
c#asp.netasp.net-mvcexceptionasp.net-membership

MemberShipException during the User Register at ASP.NET


I'm using the ASP.NET MVC 4 template to create my application, in my method Register POST, i put a block that call the UserProfile and save new information, on this case, it will save UserType.

The problem is: Every time that I'll save the user, the exception MembershipCreateUserException is called and the following message is displayed on the page: User name already exists. Please enter a different user name. The User is saved on Database.

This is my method Register:

public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user

                try
                {

                   // var user = new UserProfile() { UserName = model.UserName };

                    WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
                    WebSecurity.Login(model.UserName, model.Password);
                    return RedirectToAction("Index", "Home");

                }
                catch (MembershipCreateUserException e)

                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
//new code
                using (UsersContext db = new UsersContext())
                {

                    // Insert name into the profile table
                    UserProfile newUser = db.UserProfiles.Add(new UserProfile { UserName = model.UserName, UserType = model.UserType });
                    db.SaveChanges();

                }
            }

Anybody knows how can i resolve it? Every help will be valid! Thanks guys.


Solution

  • The following line adds a new user:

    WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
    

    And this line does it again:

    UserProfile newUser = db.UserProfiles.Add(new UserProfile { UserName = model.UserName, UserType = model.UserType });
    

    Try instead the following to add the user type when creating the user, make sure UserType is part of your RegisterModel model:

    WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { UserType = model.UserType});
    

    So the entire Register method will look like this:

    public ActionResult Register(RegisterModel model)
            {
                if (ModelState.IsValid)
                {
                    // Attempt to register the user
    
                    try
                    {
                       WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { UserType = model.UserType });
    
                       return RedirectToAction("Index", "Home");
    
                    }
                    catch (MembershipCreateUserException e)
                    {
                        ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                    }
                }