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

Wal*_*art 14 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
            })
        });
    }
Run Code Online (Sandbox Code Playgroud)

我收到了错误

'你调用的对象是空的.'

在线:

return View(new EditUserViewModel()
Run Code Online (Sandbox Code Playgroud)

当我尝试:

    //
    // 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);
    }
Run Code Online (Sandbox Code Playgroud)

我收到了错误

'你调用的对象是空的.'

在线:

ViewBag.RoleId = new SelectList(RoleManager.Roles, "Id", "Name");
Run Code Online (Sandbox Code Playgroud)

我错过了配置设置吗?

在控制器的开头我定义:

    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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

Tob*_*ias 40

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