用户角色管理 - 帐户控制器中的空引用异常

时间:2017-04-20 19:36:05

标签: c# asp.net asp.net-mvc user-roles

我发现了一个与我非常相似的问题。

MVC5 Account Controller null reference exception

我只是对这个问题发表评论并提出这个问题,但唉,我没有足够的评论意见。

这是我的RoleController

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult RoleAddToUser(string UserName, string RoleName)
    {
        ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
         // var account = new AccountController();
        // if (user!=null) UserManager.AddToRole(user.Id, RoleName);
        if (user != null) UserManager.AddToRole(user.Id, RoleName);


        ViewBag.ResultMessage = "Role created successfully !";

        // prepopulat roles for the view dropdown
        var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
        ViewBag.Roles = list;

        return View("ManageUserRoles");
    }

这是我的ManageUserRoles.cshtml视图页面

    @{
       ViewBag.Title = "ManageUserRoles";
     }

    <h2>Manage User Roles</h2>
    @Html.ActionLink("Create New Role", "Create") | @Html.ActionLink("Manage User Role", "ManageUserRoles")
    <hr />
       <h2>Role Add to User</h2>

      @using (Html.BeginForm("RoleAddToUser", "Role"))
     {
       @Html.AntiForgeryToken()
       @Html.ValidationSummary(true)

      <p>
       Username : @Html.TextBox("UserName")
       Role Name: @Html.DropDownList("RoleName", (IEnumerable<SelectListItem>)ViewBag.Roles, "Select ...")

     </p>

<input type="submit" value="Save" />
 }
   <hr />
   <h3>Get Roles for a User</h3>
   @using (Html.BeginForm("GetRoles", "Role"))
   {
       @Html.AntiForgeryToken()
   <p>
    Username : @Html.TextBox("UserName")
    <input type="submit" value="Get Roles for this User" />
</p>
    }

   @if (ViewBag.RolesForThisUser != null)
   {
       <div style="background-color:yellow;">
       <h3>Roles for this user </h3>
       <ol>
           @foreach (string s in ViewBag.RolesForThisUser)
        {
            <li>@s</li>
        }
    </ol>
</div>
    }

    <hr />
    <h3>Delete A User from a Role</h3>

    @using (Html.BeginForm("DeleteRoleForUser", "Role"))
   {
      @Html.AntiForgeryToken()
      @Html.ValidationSummary(true)

  <p>
    Username : @Html.TextBox("UserName")
    Role Name: @Html.DropDownList("RoleName", (IEnumerable<SelectListItem>)ViewBag.Roles, "Select ...")

</p>

<input type="submit" value="Delete this user from Role" />
}

我的AccountController和Startup.Auth.cs与我上面链接的帖子中的问题相同。 我尝试了那个问题上接受的答案,当我试图摆脱&#34;帐户&#34;在UserManager.AddToRole之前,它为UserManager加上了错误&#34;使用泛型类型&#39; UserManager&#39;需要2个类型参数&#34;。

当我在UserManager.AddToRole(我已经注释掉的代码行)之前添加帐户时,我得到NullReferenceException错误&#34;对象引用未设置为对象的实例&#34;在该行的AccountController中:

return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();

我完全不知所措!

0 个答案:

没有答案
相关问题