gpt4 book ai didi

c# - 使用自定义角色在 ASP.NET Identity 中初始化 RoleManager

转载 作者:IT王子 更新时间:2023-10-29 04:53:52 33 4
gpt4 key购买 nike

我使用教程 here 将用户数据库的主键从字符串更改为整数,但我在初始化角色管理器时遇到困难。它曾经使用初始化

var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));

如何使用新数据创建角色管理器?

更新:我正在使用 MVC 5 和 EF 6。

最佳答案

您的 ApplicationRoleManager 可能如下所示。因为您必须从您的 customRole 类而不是 IdentityRole 继承。

public class ApplicationRoleManager : RoleManager<CustomRole, int>
{
public ApplicationRoleManager(IRoleStore<CustomRole, int> roleStore)
: base(roleStore)
{
}

public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
{
return new ApplicationRoleManager(new RoleStore<CustomRole, int, CustomUserRole>(context.Get<ApplicationDbContext>()));
}
}

然后将以下代码添加到 Startup.Auth.cs 类(如果当前不存在)。

app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

然后您可以创建和管理角色。

    var roleManager = HttpContext.GetOwinContext().Get<ApplicationRoleManager>();

const string roleName = "Admin";

//Create Role Admin if it does not exist
var role = roleManager.FindByName(roleName);
if (role == null)
{
role = new CustomRole();
role.Id = 1; // this will be integer
role.Name = roleName;

var roleresult = roleManager.Create(role);
}

希望这对您有所帮助。

关于c# - 使用自定义角色在 ASP.NET Identity 中初始化 RoleManager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26174576/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com