Search code examples
asp.net-mvcauthenticationuser-registrationuserid

ASP.NET MVC get userId when creating user?


I want to get UserId When registering

[AllowAnonymous]
    [HttpPost]
    public ActionResult Register(RegisterModel model)
    {
        if (ModelState.IsValid)
        {
            // Attempt to register the user
            MembershipCreateStatus createStatus;
            Membership.CreateUser(model.UserName, model.Password, model.Email, passwordQuestion: null, passwordAnswer: null, isApproved: true, providerUserKey: null, status: out createStatus);

            if (createStatus == MembershipCreateStatus.Success)
            {
                FormsAuthentication.SetAuthCookie(model.UserName, createPersistentCookie: false);
                //Object reference not set to an instance of an object.
                Guid id = (Guid)System.Web.Security.Membership.GetUser().ProviderUserKey;
                System.Web.Security.Roles.AddUserToRole(model.UserName, "User");
                return RedirectToAction("Index", "Home");
            }
            else
            {
                ModelState.AddModelError("", ErrorCodeToString(createStatus));
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

But occur error("Object reference not set to an instance of an object."). How Do I get the userId in register method?

Thanks.


Solution

  • FormsAuthentication.SetAuthCookie authenticates the next request, System.Web.Security.Membership.GetUser() on the same request will return null:

    The SetAuthCookie method adds a forms-authentication ticket to either the cookies collection or the URL if CookiesSupported is false. The forms-authentication ticket supplies forms-authentication information to the next request made by the browser. With forms authentication, you can use the SetAuthCookie method when you want to authenticate a user but still retain control of the navigation with redirects.

    Membership.CreateUser returns the created user, so you should just be able to do this:

    [AllowAnonymous]
    [HttpPost]
    public ActionResult Register(RegisterModel model)
    {
        if (ModelState.IsValid)
        {
            // Attempt to register the user
            MembershipCreateStatus createStatus;
            MembershipUser membershipUser = Membership.CreateUser(model.UserName, model.Password, model.Email, passwordQuestion: null, passwordAnswer: null, isApproved: true, providerUserKey: null, status: out createStatus);
    
            if (createStatus == MembershipCreateStatus.Success)
            {
                FormsAuthentication.SetAuthCookie(model.UserName, createPersistentCookie: false);
                Guid id = (Guid)membershipUser.ProviderUserKey;
                ...