繁体   English   中英

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

[英]Get role/s of current logged in user in ASP.NET Core MVC

如何在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);

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

您可能需要考虑尝试通过FindByEmail()或其他方法加载实际的ApplicationUser对象,并将该对象传递给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);

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

[HttpPost("Auth/SignIn")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SignIn(SignInViewModel model, string returnUrl = null)
{
    ViewData["ReturnUrl"] = returnUrl;
    if (ModelState.IsValid)
    {
        var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, true, false);
        if (result.Succeeded)
        {
            // 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);

            // Do something with the roles here
        }
        else
        {
            // Uh oh....
        }
    }

    // Something is probably wrong, provide the form again....
    return View(model);
}

简短但有用:

[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;
    }
}

希望它有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM