ASP.NET Identity 2.0 RoleManager.Roles'对象引用未设置为对象的实例。'

时间:2014-05-28 21:47:01

标签: asp.net-mvc asp.net-identity

我将ASP.NET Identity 2.0与ASP.NET MVC 5和EF 6项目一起使用。

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

在我的useradmin控制器中,我有:

    //
    // 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
            })
        });
    }

我收到错误

  

&#39;对象引用未设置为对象的实例。&#39;

在线:

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

我收到错误

  

&#39;对象引用未设置为对象的实例。&#39;

在线:

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

1 个答案:

答案 0 :(得分:39)

问题是,正如我们发现的那样,您忘记为每个请求创建ApplicationRoleManager的实例。将app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);添加到App_Start / Startup.Auth.cs并且您很好。 :)