3

我想在注册时获取 UserId

[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);
    }

但是发生错误(“对象引用未设置为对象的实例。”)。如何在注册方法中获取 userId?

谢谢。

4

1 回答 1

5

FormsAuthentication.SetAuthCookie验证下一个请求,System.Web.Security.Membership.GetUser()在同一个请求上将返回 null:

如果 CookiesSupported 为 false,SetAuthCookie 方法将表单身份验证票添加到 cookie 集合或 URL。forms-authentication ticket 为浏览器发出的下一个请求提供表单认证信息。使用表单身份验证,当您想要对用户进行身份验证但仍保留对重定向导航的控制时,可以使用 SetAuthCookie 方法。

Membership.CreateUser返回创建的用户,所以你应该能够做到这一点:

[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;
            ...
于 2012-04-21T11:43:32.777 回答