![](/img/trans.png)
[英]ASP.Net Core how to get the user role in EF Core and Identity
[英]Role Manager UI ASP.NET CORE Identity & EF
我在 Microsoft 網站和其他網站上找到的教程和材料的幫助下,創建了一個小型車隊管理應用程序。
我設法實現了用戶管理服務(從一開始就沒有使用身份驗證創建項目),現在可以創建新用戶並從界面管理它們,盡管我創建了一個“管理員”角色並將其分配給管理員帳戶(通過啟動.cs) ,我很難創建一個 UI 來管理角色(創建、修改、刪除、為用戶分配角色)。 我已經搜索了 3 天,但找不到有關如何使用 RoleManager 為其創建控制器和視圖的正確教程。
任何人都可以指出我正確的方向嗎?
我正在使用 ASP.NECore.All 2.0.6 & EF Core 2.1.1
帳戶控制器:
public class AccountController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IEmailSender _emailSender;
private readonly ILogger _logger;
public AccountController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IEmailSender emailSender,
ILogger<AccountController> logger)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
_logger = logger;
}
管理控制器:
public class ManageController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IEmailSender _emailSender;
private readonly ILogger _logger;
private readonly UrlEncoder _urlEncoder;
private const string AuthenticatorUriFormat = "otpauth://totp/{0}:{1}?secret={2}&issuer={0}&digits=6";
private const string RecoveryCodesKey = nameof(RecoveryCodesKey);
public ManageController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IEmailSender emailSender,
ILogger<ManageController> logger,
UrlEncoder urlEncoder)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
_logger = logger;
_urlEncoder = urlEncoder;
}
其余操作是默認操作,您在使用個人帳戶身份驗證創建新項目時會獲得這些操作。
您可以使用由 asp.net 核心身份實現提供的IdentityRole
類。 首先,將角色管理器添加到您的類中並注入它。
private readonly RoleManager<IdentityRole> _roleManager;
在構造函數中傳遞RoleManager<IdentityRole>
並添加
_rolemanager = rolemanager
要創建新角色,請在您的視圖和控制器中使用IdentityRole
public IActionResult AddRole()
{
var role = new IdentityRole
{
Name = "Customer", //Name will be sufficient
};
_roleManager.CreateAsync(role); //role actually comes as parameter from view
return View();
}
在您的用戶創建和更新視圖中,您可以讀取所有角色並創建一個下拉列表(使用多選來分配多個角色)。
public IList<IdentityRole> GetAllRoles()
{
return _roleManager.Roles.ToList();
}
最后,在添加/更新用戶時,您現在應該將它們分配給角色。
//single
_userManager.AddToRoleAsync(user, role); //role should be role name
//multiple
_userManager.AddToRolesAsync(user, roles); // roles should be list of role names
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.