获取 ASP.NET MVC 中的角色列表

kez*_*kez 2 c# asp.net-mvc asp.net-mvc-4 asp.net-identity role-manager

我有以下方法来获取存储在中的角色列表AspNetRoles

    [AllowAnonymous]
    public async Task<ActionResult> Register()
    {
        //Get the list of Roles
        ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync(), "Name", "Name");

        return View();
    }
Run Code Online (Sandbox Code Playgroud)

然后我看到它如下

    <div class="form-group">
        <label class="col-md-2 control-label">
            Select User Role
        </label>
        <div class="col-md-10">
            @foreach (var item in (SelectList)ViewBag.RoleId)
            {
                <input type="checkbox" name="SelectedRoles" value="@item.Value" class="checkbox-inline" />
                @Html.Label(item.Value, new { @class = "control-label" })
            }
        </div>
    </div>
Run Code Online (Sandbox Code Playgroud)

但是一旦我加载页面,我就会收到Object reference not set to an instance of an object.错误

第 175 行:ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync(), "Name", "Name");

这是RoleManager定义

    public ApplicationRoleManager RoleManager
    {
        get
        {
            return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
        }
        private set
        {
            _roleManager = value;
        }
    }
Run Code Online (Sandbox Code Playgroud)

这是ApplicationRoleManager模型

// Configure the RoleManager used in the application. RoleManager is defined in the ASP.NET Identity core assembly
public class ApplicationRoleManager : RoleManager<ApplicationRole>
{
    public ApplicationRoleManager(IRoleStore<ApplicationRole, string> roleStore)
        : base(roleStore)
    {
    }

    public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
    {
        return new ApplicationRoleManager(new ApplicationRoleStore(context.Get<ApplicationDbContext>()));
    }
}
Run Code Online (Sandbox Code Playgroud)

Ric*_*ckL 5

在 Startup.Auth 中,像这样引用 RoleManager:

    public void ConfigureAuth(IAppBuilder app)
    {
        // Add this reference
        app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
    }
Run Code Online (Sandbox Code Playgroud)

确保您的控制器包含此构造函数:

        // Include this
        private ApplicationRoleManager _roleManager;
        // You already have this
        public ApplicationRoleManager RoleManager { get { return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>(); } private set { _roleManager = value; } }
Run Code Online (Sandbox Code Playgroud)

重建,再试一次,希望这能解决问题。