gpt4 book ai didi

asp.net-mvc - ASP.NET 身份 2.0 RoleManager.Roles 'Object reference not set to an instance of an object.'

转载 作者:行者123 更新时间:2023-12-01 22:18:02 24 4
gpt4 key购买 nike

我正在将 ASP.NET Identity 2.0 与 ASP.NET MVC 5 和 EF 6 项目结合使用。

我正在尝试编辑与用户关联的角色。

在我的用户管理 Controller 中,我有:

    //
// GET: /Users/Edit/1
public async Task<ActionResult> Edit(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var user = await UserManager.FindByIdAsync(id);
if (user == null)
{
return HttpNotFound();
}

var userRoles = await UserManager.GetRolesAsync(user.Id);

return View(new EditUserViewModel()
{
Id = user.Id,
Email = user.Email,
RolesList = RoleManager.Roles.ToList().Select(x => new SelectListItem()
{
Selected = userRoles.Contains(x.Name),
Text = x.Name,
Value = x.Name
})
});
}

我收到错误

'Object reference not set to an instance of an object.'

行:

return View(new EditUserViewModel()

当我尝试时:

    //
// GET: /Users/Edit/1
public async Task<ActionResult> Edit(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}

ViewBag.RoleId = new SelectList(RoleManager.Roles, "Id", "Name");

var user = await UserManager.FindByIdAsync(id);
if (user == null)
{
return HttpNotFound();
}
return View("EditUser", user);
}

我收到错误

'Object reference not set to an instance of an object.'

行:

ViewBag.RoleId = new SelectList(RoleManager.Roles, "Id", "Name");

我是否缺少配置设置?

在 Controller 的开头我定义:

    public UserManagementController(ApplicationUserManager userManager, ApplicationRoleManager roleManager)
{
UserManager = userManager;
RoleManager = roleManager;
}

private ApplicationUserManager _userManager;
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}

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

最佳答案

正如我们发现的,问题是您忘记为每个请求创建一个 ApplicationRoleManager 实例。添加app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);到 App_Start/Startup.Auth.cs 就可以了。 :)

关于asp.net-mvc - ASP.NET 身份 2.0 RoleManager.Roles 'Object reference not set to an instance of an object.',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23922424/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com