【发布时间】:2016-06-20 16:29:57
【问题描述】:
我有以下方法来获取存储在AspNetRoles中的角色列表
[AllowAnonymous]
public async Task<ActionResult> Register()
{
//Get the list of Roles
ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync(), "Name", "Name");
return 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. 错误
第 175 行:ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync(), "名称", "名称");
这是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>()));
}
}
【问题讨论】:
-
@IMU 实际上我想获得可用的角色,而不是分配用户的角色或当前用户
-
@dotctor 感谢您的建议,但我很好地阅读了这个问题 :)
标签: c# asp.net-mvc asp.net-mvc-4 asp.net-identity role-manager