【问题标题】:Add role to new user not working向新用户添加角色不起作用
【发布时间】:2015-03-27 07:33:54
【问题描述】:

我更新了 Identity 2.0 代码,为名字和姓氏添加了我自己的用户属性,然后将用户添加到默认角色“用户”。

var account = new AccountController();
account.UserManager.AddToRole(user.Id, "user");

但是,它不起作用并说帐户为空。

谁能指出问题出在哪里?

public async Task<ActionResult> Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser {
            UserName = model.Email,
            Email = model.Email
        };

        //Add our custom properties
        user.Fname = model.Fname;
        user.Lname = model.Lname;

        var result = await UserManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            var account = new AccountController();
            account.UserManager.AddToRole(user.Id, "user");

            await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
       ....

【问题讨论】:

  • 为什么要启动AccountController?只需像之前创建用户时一样使用 UserManager
  • 你的意思是使用 user.Roles.Add(theRole) 还是 UserManager.AddToRole(user.Id, "cell") ?

标签: asp.net asp.net-mvc-5 asp.net-identity-2


【解决方案1】:

感谢@Horizo​​n_Net - 这行得通:

UserManager.AddToRole(user.Id, "user")

【讨论】:

    猜你喜欢
    • 2017-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-03
    • 2018-09-10
    • 1970-01-01
    相关资源
    最近更新 更多