ASP.NET Core WebApi EF:向用户添加角色

时间:2018-05-18 08:03:36

标签: asp.net-core asp.net-identity

当我向我的用户添加一个角色(下面的代码)时,它不会添加到AspNetRoles表中,但应该添加吗?

var userResult = await _userManager.CreateAsync (admin, AdminPassword);
var roleResult = await _userManager.AddToRoleAsync (admin, Roles.AdminRole);

当我将授权属性附加到这样的方法:(Roles = Roles.AdminRole)时,它表示我没有权限:403 Forbidden。

此外,当我尝试获取用户的角色时,它会返回一个空数组:

return await _userManager.GetRolesAsync(user);

这是我的API方法:

// Host/api/roles/createrole
[Authorize(Roles = Roles.AdminRole)]
[HttpPost]
public async Task<IActionResult> CreateRole([FromBody] CreateRoleViewModel model)
{
    if (!ModelState.IsValid)
        return BadRequest();

    var result = await _roleManager.CreateAsync(new IdentityRole(model.RoleName));

    if (!result.Succeeded)
        return BadRequest(result);

    return Ok();
}

这是我的初始化:

public void Initialize()
{
    InitializeRoles();
    InitializeAdmin();     
}

#region Private Methods

private void InitializeRoles()
{
    if (_roleManager.Roles.Any())
        return;

    var role = new IdentityRole(Roles.AdminRole);
    var roleResult = _roleManager.CreateAsync(role).Result;
}

private void InitializeAdmin()
{
    if (_userManager.Users.Any())
        return;

    var admin = new User
    {
        UserName = AdminUsername,
        Email = AdminUsername,
    };

    var userResult = _userManager.CreateAsync(admin, AdminPassword).Result;
    var roleResult = _userManager.AddToRoleAsync(admin, Roles.AdminRole).Result;
}

0 个答案:

没有答案