获取ASP.NET Core MVC中当前登录用户的角色

时间:2016-05-31 11:52:54

标签: c# asp.net-core asp.net-core-mvc user-roles

如何在ASP.NET Core MVC中获取登录用户的角色?我想在用户登录应用程序后立即获取角色详细信息,但通过使用以下代码,我无法检索角色详细信息

public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
    ViewData["ReturnUrl"] = returnUrl;
    if (ModelState.IsValid)
    {

        var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);

        if (result.Succeeded)
        {
            _logger.LogInformation(1, "User logged in.");

           bool available = User.IsInRole("Admin"); 
            return RedirectToLocal(returnUrl);
        }
        if (result.RequiresTwoFactor)
        {
            return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
        }
        if (result.IsLockedOut)
        {
            _logger.LogWarning(2, "User account locked out.");
            return View("Lockout");
        }
        else
        {
            ModelState.AddModelError(string.Empty, "Invalid login attempt.");
            return View(model);
        }
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

另外,我使用了以下方法,如

var user = new ApplicationUser { UserName = model.Email, Email = model.Email };

var userRoles = await _userManager.GetRolesAsync(user);

但是,我无法获得角色细节。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:20)

您可能需要考虑尝试通过Times或其他方法加载实际的ApplicationUser对象,并将该对象传递到FindByEmail()方法,如下所示:

GetRolesAsync()

更完整的示例可能如下所示:

// Resolve the user via their email
var user = await _userManager.FindByEmailAsync(model.Email);
// Get the roles for the user
var roles = await _userManager.GetRolesAsync(user);

答案 1 :(得分:1)

简短但有用:

[Route("api/[controller]")]
[ApiController]
public class RoleController : ControllerBase
{
    private readonly UserManager<User> userManager;

    public RoleController(
        UserManager<User> userManager
        )
    {
        this.userManager = userManager;
    }

    // GET api/role
    [HttpGet]
    [Authorize]
    public async Task<IEnumerable<string>> Get()
    {
        var userId = User.FindFirstValue(ClaimTypes.Name);
        var user = await userManager.FindByIdAsync(userId);
        var role = await userManager.GetRolesAsync(user);
        return role;
    }
}

希望有帮助。