Search code examples
asp.net-coreasp.net-core-identityasp.net-core-3.1

how to delete users including roles and users from AspnetRoleUsers


I am making a project using asp.net core 3.1 and I can't find the right source of deleting users including roles in Asp.net core 3.1 using Web.api

This is the code I have tried but seems like not appropriate but haven't tried yet. Do you have any ideas of how to realize that? I want to appropriately check the error using Web Api functions such as statuscode or any error messages to the frontend.

[HttpPost, ActionName("Delete")]
public async Task<ActionResult> DeleteUser(string id)
{


    var user = await _userManager.FindByIdAsync(id);
    var rolesForUser = await _userManager.GetRolesAsync(user); 
    if (rolesForUser.Count() > 0)
    {
        foreach (var item in rolesForUser.ToList())
        {
            // item should be the name of the role
            var result = await _userManager.RemoveFromRoleAsync(user, item);
        }
    }

    await _userManager.DeleteAsync(user);  
    return OkResult(result);
}



Solution

  • You don't need to loop the roles and delete , you can use RemoveFromRolesAsync :

    public virtual Task<IdentityResult> RemoveFromRolesAsync(TUser user, IEnumerable<string> roles);
    

    And each operation will return IdentityResult which could be used to check the operation status :

    if (User.Identity.IsAuthenticated)
    {
        try
        {
            var user = await _userManager.FindByIdAsync(id);
            var roles= await _userManager.GetRolesAsync(user);  
    
            var result =  await _userManager.RemoveFromRolesAsync(user, roles);
            if (result.Succeeded)
            {
                var resultdelete = await _userManager.DeleteAsync(user);
                if (result.Succeeded)
                {
                    return Ok();
                }
                else
                {
                    List<string> errors = new List<string>();
                    foreach (var error in result.Errors)
                    {
                        errors.Add(error.Description);
                    }
                    return BadRequest(errors);
    
                }
            }
            else
            {
                List<string> errors = new List<string>();
                foreach (var error in result.Errors)
                {
                    errors.Add(error.Description);
                }
                return BadRequest(errors);
            }
        }
        catch (Exception exception)
        {
            List<string> errors = new List<string>() { exception.Message };
            return StatusCode(StatusCodes.Status500InternalServerError, errors);
        }
    }
    

    But use database stored procedures with transaction is always a good choice .