I am trying to set role to the logged user but I can't get the logged user name in my non-action method called from another controller. I am missing something, because I get the error: "Object reference not set to an instance of an object", which I understand because the logged user name comes null in my RegisterAsUser() method. Do I call the non-action method ok? Tell me what I am doing wrong. Thank you in advance!
My code:
The non-action method:
[NonAction] [Authorize] public void RegisterAsUser() { //Add User role var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context)); string role = "User"; //Create Role User if it does not exist if (!roleManager.RoleExists(role)) { var roleResult = roleManager.Create(new IdentityRole(role)); } var store = new UserStore<ApplicationUser>(new ApplicationDbContext()); var userManager = new UserManager<ApplicationUser>(store); string userId = User.Identity.GetUserId(); if (!Roles.IsUserInRole("Admin")) { var result = userManager.AddToRole(userId, role); } } Where I call the RegisterAsUser() method in other controller:
public ActionResult Create() { //set the logged user role to "User" IdentityRoleController roleController = new IdentityRoleController(); roleController.RegisterAsUser(); ... some other code here... return View(); } Update: I noticed that If I change the non-action method with an ActionResult one and call it from the url it assigns the role to the logged user. So I assume that instantiating a controller with it's non-action method in another controller it's wrong but I will like to know why.
