Search code examples
asp.net-mvcsecurityforms-authentication

mvc set and get id and name in FormsAuthentication


How can I set and get id and name in FormsAuthentication

Here only I set name

var user = db.usertable.Where(x => x.UserName == L.UserName && x.password == L.password).FirstOrDefault();
        if (user == null)
        {
            ViewBag.Msg = "invalde user";
            return View();
        }
        else
        {
            FormsAuthentication.SetAuthCookie(user.UserName, false);
            return RedirectToAction("Index", "Home");

        }

and here only I can get name by this code:

System.Web.HttpContext.Current.User.Identity.Name

How about can I get id user?


Solution

  • When user register in your app "/Account/Register", Identity automatically creates account for him, it would create few new tables in your DB, It would store your new user data in dbo.AspNetUsers.

    You have to create Membership object which validates user credentials and manages user settings by user name. And call method ProviderUserKey to get user id.

    Membership.GetUser(User.Identity.Name).ProviderUserKey
    

    You can't change user id after creation, it's generated automatically.