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

编程入门 行业动态 更新时间:2024-10-26 21:31:08
本文介绍了获取ASP.NET Core MVC中当前登录用户的角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

How can I get the logged in user's role/s in ASP.NET Core MVC? I want to get role details as soon as user logs in into the application, but by using following code I am not able to retrieve the role details

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

此外,我使用了以下方法,例如

Also, I have used the below methods like

var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var userRoles = await _userManager.GetRolesAsync(user);

仍然,我无法获得角色详细信息.有人可以帮忙吗?

Still, I am not able to get the role details. Can anyone please help on this?

推荐答案

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

You may want to consider trying to load the actual ApplicationUser object via the FindByEmail() or some other method and passing that object into the GetRolesAsync() method as seen below :

// 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); }

更多推荐

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

本文发布于:2023-11-14 13:24:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1587330.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:角色   用户   NET   ASP   MVC

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!