MVC将用户角色返回到视图

时间:2015-01-10 17:50:35

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

我已使用以下教程http://www.dotnetfunda.com/articles/show/2898/working-with-roles-in-aspnet-identity-for-mvc向我的应用程序添加角色。我已设法将一个角色添加到存储在我的数据库中的用户。但是,我无法列出已分配给该用户的角色。我收到以下错误

对象引用未设置为对象的实例。

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

我的控制器看起来像这样

 [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult GetRoles(string UserName)
    {
        ApplicationDbContext context = new ApplicationDbContext();
        if (!string.IsNullOrWhiteSpace(UserName))
        {
            ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
            var account = new AccountController();
            //this.UserManager.GetRoles(user.Id);
            ViewBag.RolesForThisUser = account.UserManager.GetRoles(user.Id);

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

和我的观点

<hr />
<h3>Get Roles for a User</h3>
 @using (Html.BeginForm("GetRoles", "Account"))
 {
   @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>
} 

4 个答案:

答案 0 :(得分:0)

我认为您选择了一个糟糕的教程,如果您在帖子末尾阅读了评论,那么所有人都有类似的问题。顺便说一句,这篇文章很困惑。多次,创建一个AccountController实例来访问在该控制器(UserManager)上创建的对象的实例,永远将此实现直接绑定到默认AccountController的存在。

我留下了很少的好教程

ASP.NET MVC 5 Identity: Extending and Modifying Roles

ASP.NET Identity 2.0: Customizing Users and Roles

Extending Identity Accounts and Implementing Role-Based Authentication in ASP.NET MVC 5

答案 1 :(得分:0)

听起来很熟悉,前几天我注意到了这个问题。我不会将其标记为完全重复,因为我并不完全确定它是......但是你和这个人很可能都遵循相同的教程。

MVC5 Account Controller null reference exception

编辑:在进一步审核时,它看起来完全相同的问题..所以我继续投票并将其作为副本投票。

答案 2 :(得分:0)

你可以试试这个:   在Controller类中,插入:

using System.Threading.Tasks;
using Microsoft.AspNet.Identity.Owin;

接下来,控制器动作:

 [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> GetRoles(string UserName)
    {
        using (ApplicationDbContext context = new ApplicationDbContext())
        {
            if (!string.IsNullOrWhiteSpace(UserName))
            {

                ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();

                //var account = new AccountController();
                ApplicationUserManager UserManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
                //this.UserManager.GetRoles(user.Id);

                ViewBag.RolesForThisUser = await UserManager.GetRolesAsync(user.Id);
                // 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");
        }
    }

视图没问题。请告诉我是否适合你。

答案 3 :(得分:0)

感谢大家的回复。我已设法通过使用以下内容返回用户角色。

 [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult GetRoles(string UserName)
    {
        ApplicationDbContext context = new ApplicationDbContext();
        if (!string.IsNullOrWhiteSpace(UserName))
        {
            ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();

            var ReturnRole = this.UserManager.GetRoles(user.Id);
           // ViewBag.RolesForThisUser = account.UserManager.GetRoles(user.Id);
            ViewBag.RolesForThisUser = ReturnRole;
            // 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");
    }

Stefan Vlad的上述文章也将有效:)谢谢Stefan

我现在需要的是删除用户的角色,希望对此!