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

标签 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();
    }

然后我得到它的 View 如下

    <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>

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

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

这是 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>()));
    }
}

最佳答案

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

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

确保您的 Controller 包含此构造函数:

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

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

关于c# - 获取 ASP.NET MVC 中的角色列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35838390/

相关文章:

C#在每个循环中从列表中获取随机整数

c# - 为网站抓取工具实现的 TPL 数据流

c# - SaveChangesAsync 不更新数据库表中的值

c# - 如何使用 Autofac 根据用户上下文解析组件

knockout.js - 我可以在 knockout 验证中手动添加错误消息吗?

javascript - 如何在asp.net MVC4中将模型从 View 传递给javascript

c# - 谁在 ASP.Net MVC Pipeline 中先执行?

c# - 关联、聚合和组合

c# - 如何在 EF4 中为多个 ObjectContext 实现单个 SQL 事务

c# - MVC5 Razor html.dropdownlistfor 当值在数组中时设置选择