使用SimpleMembershipProvider创建用户帐户

时间:2013-05-19 19:49:57

标签: asp.net-mvc-4 simplemembership

我正在使用MVC 4,我正在尝试向UserProfile添加一个名为AddedById的新字段(用于管家)。

这就是我所拥有的:

WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new
                {
                    FirstName = model.FirstName,
                    LastName = model.LastName,
                    AddedDate = DateTime.UtcNow
                    AddedByID = // to sure how to get the id because the account has not been created yet.
                });

我应该在创建帐户后更新AddById吗?

1 个答案:

答案 0 :(得分:1)

因为支持小组可以为某人创建帐户

如果是这种情况,请确保AddedByIDNullable,然后在创建Support Team之前先对User进行身份验证。

然后,让你的Register Action看起来像这样;

    //
    // POST: /Account/Register

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Register(RegisterModel model)
    {
        if (ModelState.IsValid)
        {
            // Attempt to register the user
            using (EfDb db = new EfDb())
            {                                     
                try
                {
                    var userProfile = db.UserProfiles.Local.SingleOrDefault(u => u.UserName == User.Identity.Name)
                                ?? db.UserProfiles.SingleOrDefault(u => u.UserName == User.Identity.Name);

                        WebSecurity.CreateUserAndAccount(
                            model.UserName,
                            model.Password,
                                new
                                    {
                                        FirstName = model.FirstName,
                                        LastName = model.LastName,
                                        AddedDate = DateTime.UtcNow,
                                        AddedByID = userProfile.UserId
                                    }
                            );

                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }
        }

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