Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebSecurity.CreateUserAndAccount get reference to created user

I am working on a ASP.NET MVC 4 web application. After creating a user and account (using WebSecurity.CreateUserAndAccount), i want continue working with this user, e.g. for using him as a foreign key in an other model.

One approach would be to give the UserProfile a custom UserId, and to use this UserId for querying the user. For example:

...
  try
            {
                int CustomUserId = Rnd.Next(1000000, 9999999);
                WebSecurity.CreateUserAndAccount(RegisterModel.UserName, RegisterModel.Passwordword, 
                    propertyValues: new { UserId = CustomUserId });
                WebSecurity.Login(UserName, Password);

                var UserProfile = (from UserProf in _db.UserProfiles
                              where UserProf.UserId == CustomUserId 
                              select UserProf).FirstOrDefault();

                CustomModel cm = new CustomModel();
                cm.User = UserProfile;

                //Add cm to database an so on...

                return RedirectToAction("Index", "Home");
            }
            catch (MembershipCreateUserException e)
            {
               //Bla...
            }
...

This seems to me pretty inelegant. Especially because of maintaining the UserId on my own. Is there a more elegant way to solve this Problem?

like image 771
user1324258 Avatar asked Aug 21 '13 17:08

user1324258


1 Answers

If you have UserId as an Identity column, SimpleMembership will handle it automatically. Then you can get the resulting userId with: var userId = WebSecurity.GetUserId(RegisterModel.UserName)

imho: SimpleMembership implementation is a POS. Take a look at the code, it's a big mess. It try to be flexible, but ends up not being very flexible. It's also required that the UserId is an int. Then again, if you can live with it, the benefit is the automatic integration with 3rd party authentication (facebook, twitter, etc..)

like image 200
Noogen Avatar answered Sep 19 '22 02:09

Noogen