0

I am developing asp.net MVC app and I tried to add a role to the user by following code:

        [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();
            account.UserManager.AddToRole(user.Id, RoleName);

            ViewBag.ResultMessage = "Role created successfully !";

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

But when UserManager calls AddToRole function it gives object reference error in Account Controller in the GET method in the following code:

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

I have checked user.Id and RoleName parameters and ther are not null.

Awais Mahmood
  • 1,308
  • 4
  • 21
  • 51
  • Ensured GetOwinContext() is != null ? – Alex K. Aug 05 '15 at 11:22
  • @AlexK. yes the HttpContext is null. What should I do? – Awais Mahmood Aug 05 '15 at 11:31
  • 1
    HttpContext itself is null or the result of GetOwinContext() is null? – Alex K. Aug 05 '15 at 11:33
  • This perhaps: http://stackoverflow.com/questions/223317/httpcontext-on-instances-of-controllers-are-null-in-asp-net-mvc – Alex K. Aug 05 '15 at 11:38
  • you created an instance of accountcontroller just to access UserManager? – tmg Aug 05 '15 at 11:59
  • yes. only to access that func – Awais Mahmood Aug 05 '15 at 12:05
  • but now i inherited the UserRoles controller from account controller. and the problem is solved.. but I observed a strange attitude. My app is unable to access any of the UserRoles action method unless i write [AllowAnonymous] on top of it. And if i don't write [AllowAnonymous] on top of method then it goes to Login() method of Account controller. – Awais Mahmood Aug 05 '15 at 12:11
  • account controller in default template is decorated with [Authorize] filter attribute, so your UserRoles controller inherits that as well – tmg Aug 05 '15 at 12:40

0 Answers0