初始化RoleManager在ASP.NET中的身份与自定义角色 [英] Initializing RoleManager in ASP.NET Identity with Custom Roles

查看:994
本文介绍了初始化RoleManager在ASP.NET中的身份与自定义角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我改变了从字符串用户数据库中的主键使用教程为int <一个href=\"http://www.asp.net/identity/overview/extensibility/change-primary-key-for-users-in-aspnet-identity\">here,但我有困难初始化角色管理器。它曾经使用初始化

I changed the primary key for the user database from string to int using the tutorial here, but I'm having difficulty initializing the Role Manager. It used to be initialized using

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

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

How can I create the role manager using the new data?

更新:我使用MVC 5和6 EF

Update: I'm using MVC 5 and EF 6.

推荐答案

ApplicationRoleManager 可能看起来像这样。因为你必须从你的customRole类,而不是继承 IdentityRole

Your ApplicationRoleManager may look like this. because you have to inherit from your customRole class instead of 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>()));
    }
}

然后,添加以下code到Startup.Auth.cs类,如果目前不存在。

Then add following code to Startup.Auth.cs class if not currently exists.

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

然后创建和管理角色。

Then you create and manage roles.

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

希望这有助于。

这篇关于初始化RoleManager在ASP.NET中的身份与自定义角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆