_UserManager.AddToRolesAsync()成功后,AspNetUserRoles为空

时间:2019-04-30 21:06:45

标签: asp.net-core

以下代码让我头疼。如您所见,我有一个标准的AccountController,带有“ Register”方法。注册后,应该给用户角色“ Module_All__Admin”。该代码似乎正确,并且“ resultAssigningRole.Succeeded”返回true ...为什么我的SQL数据库中的“ AspNetUserRoles”表为空?

注意:连接字符串可以正常工作,在一个单独的控制器中,我填写了“ AspNetRoles”表,并且可以正常工作。

public class AccountController : Controller
    {
        private readonly UserManager<IdentityUser> _userManager;
        private readonly SignInManager<IdentityUser> _signInManager;
        private readonly RoleManager<IdentityRole> _roleManager;
        private readonly ILogger _logger;
        private readonly IEmailSender _emailSender;

        public AccountController(
            UserManager<IdentityUser> userManager,
            SignInManager<IdentityUser> signInManager,
            RoleManager<IdentityRole> roleManager,
            ILoggerFactory loggerFactory,
            IEmailSender emailSender
            )
        {
            _userManager = userManager;
            _signInManager = signInManager;
            _roleManager = roleManager;
            _logger = loggerFactory.CreateLogger<AccountController>();
            _emailSender = emailSender;
        }

public async Task<IActionResult> Register(LoginViewModel loginViewModel)
        {
            if (ModelState.IsValid)
            {
                IdentityUser user = new IdentityUser() { UserName = loginViewModel.Email };
                IdentityResult resultCreatingUser = await _userManager.CreateAsync(user, loginViewModel.Password);
                if (resultCreatingUser.Succeeded) //this returns true
                {
                    if (await _roleManager.RoleExistsAsync("Module_All__Admin"))
                    {
                        IdentityResult resultAssigningRole = await _userManager.AddToRoleAsync(user, "Module_All__Admin");
                        if (resultAssigningRole.Succeeded) //this returns true
                        {
                            await _signInManager.SignInAsync(user, isPersistent: false);
                            _logger.LogInformation(3, "User created, assigned to role 'AllModules - User'");
                        }
                        else
                        {
                            var errors = resultAssigningRole.Errors;
                            var message = string.Join(", ", errors);
                            ModelState.AddModelError("", message);
                        }

                    }
                    return RedirectToAction("LoggedIn", "Account");
                }
            }
            return View("~/Views/Home/Index.cshtml");
        }

    }

编辑 大家,这似乎是ASP.NET CORE中的错误。我在github中发现,确保像这样设置您的服务可以解决这种情况:

        services.AddIdentity<IdentityUser, IdentityRole>()
                   .AddEntityFrameworkStores<ApplicationDbContext>()
                   .AddDefaultUI()
                   .AddDefaultTokenProviders();

对我有用。

1 个答案:

答案 0 :(得分:0)

调用_userManager.CreateAsync(...后,您的user对象是否具有ID?

如果没有,请尝试此操作。它将关闭,并通过用户名(或电子邮件,如果您愿意)从数据库中获取新用户,并使用其中的ID来分配角色。

            ...
            if (resultCreatingUser.Succeeded) //this returns true
            {
                if (await _roleManager.RoleExistsAsync("Module_All__Admin"))
                {
                    //Retrieve the user from the database by userName (or Email if unique)
                    var _newUser = await _userManager.FindByNameAsync(user.userName)

                    IdentityResult resultAssigningRole = await _userManager.AddToRoleAsync(_newUser, "Module_All__Admin");
                    if (resultAssigningRole.Succeeded) //this returns true
                    {
                        ...