0

I have used the following tutorial http://www.dotnetfunda.com/articles/show/2898/working-with-roles-in-aspnet-identity-for-mvc to add roles to my application. I have managed to add a role to a user that is stored within my database. However I am unable to list the roles that have been assigned to that user. I get the following error

Object reference not set to an instance of an object.

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

My controller looks like this

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

and my view

<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>
} 
tereško
  • 58,060
  • 25
  • 98
  • 150
MarkJClark
  • 75
  • 1
  • 2
  • 14
  • possible duplicate of [MVC5 Account Controller null reference exception](http://stackoverflow.com/questions/27750918/mvc5-account-controller-null-reference-exception) – Erik Funkenbusch Jan 11 '15 at 00:39

4 Answers4

1

You can try this : In your Controller class, insert :

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

next, the controller action :

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

The view is OK. Please let me know if works for you.

Stefan Vlad
  • 166
  • 2
  • 2
0

I think that you selected a bad tutorial, if you read the comments at the end of the post all the people has the similar problem. By the way this article is confused. Multiple times, an instance of AccountController is created to access an instance of an object created on that controller (UserManager), forever tying this implementation directly to the existence of the default AccountController.

I leave few good tutorials

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

Ignacio Laborde
  • 1,442
  • 2
  • 11
  • 10
0

This sounded familiar, and I noticed this question the other day. I won't mark it as an exact duplicate, as i'm not entirely sure that it is.. but it's quite possible that you and this person were following the same tutorial.

MVC5 Account Controller null reference exception

EDIT: On further review, it looks like exactly the same issue.. so I went ahead and voted it as a duplicate.

Community
  • 1
  • 1
Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291
0

Thanks all for the replies. I have managed to return the user roles by using the following.

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

The above Post from Stefan Vlad will also work :) Thanks Stefan

All I need now is to delete a role from a user, here's hoping !

MarkJClark
  • 75
  • 1
  • 2
  • 14