如何使用AspNet.Identity创建一个使用Asp.Net RTM位的用户?

时间:2013-10-02 18:50:13

标签: c# asp.net asp.net-identity

如何使用AspNet.Identity创建具有Asp.Net RTM位的用户?

我转到了@Hao Kung在这里发布的AspNet Identity RTM位:How can I get early access to upcoming Asp.Net Identity changes?

用于注册用户的RC Asp.Net身份代码如下所示......

protected void CreateUser_Click(object sender, EventArgs e)
{
    string userName = UserName.Text;
    var manager = new AuthenticationIdentityManager(new IdentityStore());
    User u = new User(userName) { UserName = userName };
    IdentityResult result = manager.Users.CreateLocalUser(u, Password.Text);
    if (result.Success) 
    {
        manager.Authentication.SignIn(Context.GetOwinContext().Authentication, u.Id, isPersistent: false);
        OpenAuthProviders.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
    }
    else 
    {
        ErrorMessage.Text = result.Errors.FirstOrDefault();
    }
}

我的问题类似于此处发现的问题...... How do you login/authenticate a user with Asp.Net MVC5 RTM bits using AspNet.Identity?

但我问的是创建用户,而不是登录。

2 个答案:

答案 0 :(得分:1)

这是Register方法的样子,它基本上是用密码创建用户:

    //
    // POST: /Account/Register
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model) {
        if (ModelState.IsValid) {
            var user = new ApplicationUser() { UserName = model.UserName };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded) {
                await SignInAsync(user, isPersistent: false);
                return RedirectToAction("Index", "Home");
            }
            else {
                AddErrors(result);
            }
        }

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

答案 1 :(得分:0)

不确定这是否是最佳方式,或者在RTM正式之前这是否会发生变化,但这似乎可以解决问题......

    protected void CreateUser_Click(object sender, EventArgs e)
    {
        string userName = UserName.Text;
        var manager = HttpContext.Current.GetOwinContext();
        ApplicationUser u = new ApplicationUser() { UserName = userName };
        var userMangager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>());

        IdentityResult result = userMangager.Create(u, Password.Text);
        if (result.Succeeded) 
        {
            manager.Authentication.SignIn();
            OpenAuthProviders.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
        }
        else 
        {
            ErrorMessage.Text = result.Errors.FirstOrDefault();
        }
    }