我有以下方法来获取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(等待 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>()));
}
}
答案 0 :(得分:4)
在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; } }
重建,再试一次,希望这会解决它。
答案 1 :(得分:2)
检查您的RoleManager.Roles
财产。似乎它不会从DB返回任何内容。还要确保UserRoles
表