如何使用OWIN向ASP.NET中新创建的用户添加角色

时间:2015-08-31 15:26:20

标签: asp.net asp.net-identity

如何将所有新注册用户默认设置为角色“用户”?

这是我注册新用户的代码:

[HttpPost]
public async Task<ActionResult> Register(RegisterViewModel model)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    var roleStore = new RoleStore<IdentityRole>();
    var roleManager = new RoleManager<IdentityRole>(roleStore);

    var userStore = new UserStore<IdentityUser>();
    var userManager = new UserManager<IdentityUser>(userStore);                            

    var user = await userManager.FindAsync(model.Username, model.Password);

    if (user != null)
    {
        ModelState.AddModelError(string.Empty, "The user already exists.");
        return View();
    }
    user = new IdentityUser { UserName = model.Username,Email = model.Email, };
    await userManager.CreateAsync(user, model.Password);           

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

1 个答案:

答案 0 :(得分:2)

SELECT y0_
FROM (
    SELECT this_.ADD_Id AS y0_
    FROM ADDRESSES this_
    WHERE (
            this_.CUS_Id = 3942425
            AND this_.ADD_ISMAIN = 'AAAAAAAAAA'
            )
    )
WHERE rownum <= 1

如果由于任何原因await userManager.CreateAsync(user, model.Password); if (!roleManager.RoleExists("User")) roleManager.Create(new IdentityRole("User")); userManager.AddToRole(adminUser.Id, "User"); 剂量未更新,请使用此:

ID