简体   繁体   中英

Asp.net MVC 5, Identity 2.0 Unable to add a Role to user

i am trying to add a role to a specific user using controllers. But, i am getting error

Here my Role Controller:

[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 !";

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

Here is my Action Controller:

public class AccountController : Controller
{
    private ApplicationUserManager _userManager;

    public AccountController()
    {
    }

    public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager )
    {
        UserManager = userManager;
        SignInManager = signInManager;
    }

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

This is the error i am getting:

Server Error in '/' Application.

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 32:             get
Line 33:             {
Line 34:                 return _userManager ??      HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
Line 35:             }
Line 36:             private set

The error, "Object reference not set to an instance of an object.", means that you have some variable that you're calling a property or method on that is evaluating to null at runtime.

For example, you're pulling a user out of the database and then later referencing its Id property, ie user.Id . But, if no user was found, your user variable is actually null , and null does not have a property Id , hence the error.

Any time you have a variable that could either be an instance of a type or null, you need to check for a null value before using it to ensure that you don't get a runtime error like this.

if (user != null)
{
    // use your `user` variable here
}

Now, I'm not sure if your user variable is actually null. It might be something else, but this is the kind of thing you should look for when debugging an error like this. Run the debugger in Visual Studio and inspect all your variables in the action. If any are null, that's most likely your candidate.

Also, please, for the love of everything good and holy in the world, do not instantiate a controller in an action in another controller, especially just to get at the UserManager in AccountController by default. Either add the same property to each controller that needs it, as AccountController does, or even better, inject it into your controllers via a DI (dependency injection) container and set it to request-scope.

Try this,

Add Rolemanger class property and add in AccountController .

 public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager, ApplicationRoleManager roleManager)
 {
        UserManager = userManager;
        SignInManager = signInManager;
       RoleManager =roleManager;
 }

 private ApplicationRoleManager _roleManager;
 public ApplicationRoleManager RoleManager
 {
        get
        {
            return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
        }
        private set
        {
            _roleManager = value;
        }
 }

After add this in your page. user this assign role to user. pass your user's id userId and rolename which role you want to assign to user.

var result = UserManager.AddToRole(userId, "RoleName");

Add this in Startup.Auth.cs file in App_Start Folder

app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

As the below:

public void ConfigureAuth(IAppBuilder app)
    {
        // Configure the db context, user manager and signin manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

        ...
        ...
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM