Search code examples
asp.net-mvcasp.net-mvc-4simplemembershipuser-managementuserid

Save userid on database when create new object


I have a Controller where on the Create action I need the user ID.

Here's the controller.

    public ActionResult Create(MyCreateViewModel model)
    {
        if (ModelState.IsValid)
        {
            var myobject = new MyObject
            {
                Attrib1 = DateTime.Now.Date,
                Attrib2 = model.Etichetta,
                UserId = // I need the user ID...
            };

            // Save the object on database...                

            return RedirectToAction("Index");
        }
        return View(model);
    }

I'm using the UserProfile table provided with the SimpleMembership of MVC 4.

Which is the best practice in MVC 4 to manage the userID across the application?

Do I have to include a User attribute inside every Entity class?

Should I use a Session[] variable or what?


Solution

  • You can use this line to get the userId from the UserProfiles table.

    var userId = WebSecurity.GetUserId(HttpContext.Current.User.Identity.Name);
    

    You can also use this function to get the users complete profile, including any custom columns you may be populating.

    public static UserProfile GetUserProfile()
            {
                using (var db = new UsersContext())
                {
                    var userId = WebSecurity.GetUserId
                                (HttpContext.Current.User.Identity.Name);
                    var user = db.UserProfiles
                                 .FirstOrDefault(u => u.UserId == userId);
                    if (user == null)
                    {
                        //couldn't find the profile for some reason
                        return null;
                    }
                    return user;
                }
            }