简体   繁体   English

Asp.net MVC 5,Identity 2.0无法向用户添加角色

[英]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. 说明:执行当前Web请求期间发生未处理的异常。 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. 异常详细信息:System.NullReferenceException:对象引用未设置为对象的实例。

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. 错误“对象引用未设置为对象的实例。”,意味着您要调用的某个变量的属性或方法在运行时评估为null。

For example, you're pulling a user out of the database and then later referencing its Id property, ie user.Id . 例如,您user.Id数据库中拉出用户,然后再引用其Id属性,即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. 但是,如果未找到用户,则您的user变量实际上为null ,并且null没有属性Id ,因此发生错误。

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. 每当您拥有一个可能是类型实例或null实例的变量时,都需要在使用null值之前检查它,以确保不会出现这样的运行时错误。

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

Now, I'm not sure if your user variable is actually null. 现在,我不确定您的user变量是否实际上为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. 在Visual Studio中运行调试器,并检查操作中的所有变量。 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. 另外,为了爱世界上所有美好而神圣的事物,请不要在另一个控制器中的操作中实例化一个控制器,尤其是默认情况下仅在AccountController中使用UserManager 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. 可以像AccountController一样向需要的每个控制器添加相同的属性,或者甚至更好的方法是,通过DI(依赖项注入)容器将其注入到控制器中,并将其设置为request-scope。

Try this, 尝试这个,

Add Rolemanger class property and add in AccountController . 添加Rolemanger类属性并添加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. 传递您用户的ID userIdrolename要将您要分配给用户的角色。

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

Add this in Startup.Auth.cs file in App_Start Folder 将其添加到App_Start文件夹的Startup.Auth.cs文件中

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

        ...
        ...
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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