ASP.NET MVC Membership,获取新的UserID

时间:2010-06-12 15:11:18

标签: c# asp.net-mvc asp.net-membership

我正在尝试注册一个新用户,并且还了解如何获取新的userID,以便我可以开始创建自己的用户表,其中userID映射到asp.net成员资格用户表。

以下是我的代码:

 [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Register(string userName, string email, string position, string password, string confirmPassword)
    {

        ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
        ViewData["position"] = new SelectList(GetDeveloperPositionList());

        if (ValidateRegistration(userName, email, position, password, confirmPassword))
        {
            // Attempt to register the user
            MembershipCreateStatus createStatus = MembershipService.CreateUser(userName, password, email);

            if (createStatus == MembershipCreateStatus.Success)
            {
                FormsAuth.SignIn(userName, false /* createPersistentCookie */);

                return RedirectToAction("Index", "Home");
            }
            else
            {
                ModelState.AddModelError("_FORM", ErrorCodeToString(createStatus));
            }
        }

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

我做了一些研究,许多网站通知我使用Membership.GetUser()。ProviderUserKey;但是当Membership为NULL时会抛出错误。

我把这行代码放在“return RedirectToAction(”Index“,”Home“)之上;”在if语句中。

请有人可以告诉我这个......

提前致谢

2 个答案:

答案 0 :(得分:1)

使用MembershipProvider创建用户,这将返回MembershipUser实例。您可以在哪里访问ProviderKey以访问Id。

MembershipCreateStatus status;
MembershipUser user = Membership.Provider.CreateUser(userName, password, email, null, null, true, null, out status);
if (status == MembershipCreateStatus.Success)
{
   object key = user.ProviderUserKey;
}

答案 1 :(得分:0)

这将检索ProviderKey:

if (createStatus == MembershipCreateStatus.Success)
{
     FormsAuth.SignIn(userName, false /* createPersistentCookie */);

     MembershipUser newUser = Membership.GetUser(model.UserName);
     string key = newUser.ProviderUserKey.ToString();

     return RedirectToAction("Index", "Home");
}