如何添加AuthController添加角色默认IdentityCore

时间:2018-08-29 14:55:43

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

在注册用户期间使用IdentityCore时如何添加默认角色: 我的AuthController并使用UserMenager和SignInManager类,IConfiguration,我想在用户注册期间添加一个角色。我有3个负责用户和角色的模型。一个用户可以有多个角色,但是在此他假设该用户具有一个角色,例如一个学生,一个角色可以有多个用户。

pointerId

模型数据库UserRole:

[AllowAnonymous]
[Route("api/[controller]")]
[ApiController]
public class AuthController : ControllerBase
{
    private readonly IConfiguration _config;
    private readonly IMapper _mapper;
    private readonly UserManager<User> _userManager;
    private readonly SignInManager<User> _signInManager;

    public AuthController(IConfiguration config,
        IMapper mapper,
        UserManager<User> userManager,
        SignInManager<User> signInManager)
    {
        _userManager = userManager;
        _signInManager = signInManager;
        _mapper = mapper;
        _config = config;
    }

    [HttpPost("register")]
    public async Task<IActionResult> Register(UserForRegisterDto userForRegisterDto)
    {
        var userToCreate = _mapper.Map<User>(userForRegisterDto);

        var result = await _userManager.CreateAsync(userToCreate, userForRegisterDto.Password);

        var userToReturn = _mapper.Map<UserForDetailedDto>(userToCreate);

        if (result.Succeeded)
        {
            return CreatedAtRoute("GetUser", 
                new { controller = "Users", id = userToCreate.Id }, userToReturn);
        }

        return BadRequest(result.Errors);
    }

模型角色:

public class UserRole : IdentityUserRole<int>
{
    public User User { get; set; }
    public Role Role { get; set; }
}

模型用户

public class Role : IdentityRole<int>
{
    public ICollection<UserRole> UserRoles { get; set; }
}

1 个答案:

答案 0 :(得分:1)

您可以检索使用User创建的CreateAsync(),然后使用UserManager.AddToRoleAsync()

var result = await _userManager.CreateAsync(userToCreate, userForRegisterDto.Password);
User newUser = _userManager.Users.First(x => x.Email == userForRegisterDto.Email);
var roleResult = await _userManager.AddToRoleAsync(newUser, "YourDefaultRoleName");