【问题标题】:Asp.net MVC 5, Identity 2.0 Unable to add a Role to userAsp.net MVC 5,Identity 2.0 无法向用户添加角色
【发布时间】:2015-02-01 04:44:58
【问题描述】:

我正在尝试使用控制器向特定用户添加角色。但是,我收到错误

这是我的角色控制器:

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

这是我的动作控制器:

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

这是我得到的错误:

“/”应用程序中的服务器错误。

对象引用未设置为对象的实例。

说明:在执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

异常详细信息:System.NullReferenceException:对象引用未设置为对象的实例。

来源错误:

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

【问题讨论】:

    标签: asp.net asp.net-mvc-5 asp.net-identity-2


    【解决方案1】:

    试试这个,

    添加 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;
            }
     }
    

    在您的页面中添加此内容后。用户此分配角色给用户。将您的用户 ID userIdrolename 传递给您要分配给用户的角色。

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

    【讨论】:

      【解决方案2】:

      错误“未将对象引用设置为对象的实例。”表示您有一些变量,您正在调用某个变量的属性或方法,该变量在运行时评估为 null。

      例如,您将用户从数据库中拉出,然后引用其Id 属性,即user.Id。但是,如果没有找到用户,您的 user 变量实际上是 null,并且 null 没有属性 Id,因此会出现错误。

      任何时候你有一个变量可以是一个类型的实例或空值,你需要在使用它之前检查空值,以确保你不会遇到这样的运行时错误。

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

      现在,我不确定您的 user 变量是否实际上为空。它可能是别的东西,但这是你在调试这样的错误时应该寻找的东西。在 Visual Studio 中运行调试器并检查操作中的所有变量。如果有任何一个为空,那很可能是您的候选人。

      另外,为了世上所有美好和神圣的事物,请不要在另一个控制器的动作中实例化一个控制器,尤其是为了在@987654328 中获得UserManager @ 默认。可以像AccountController 那样将相同的属性添加到需要它的每个控制器,或者更好的是,通过 DI(依赖注入)容器将其注入您的控制器并将其设置为请求范围。

      【讨论】:

      • 我已在调试模式下检查,我正在获取用户 ID
      • 正如我所说,它可能不是user,它是空的。我只是用它作为例子。 Something 为空。找到它,你就会解决你的问题。
      【解决方案3】:

      将此添加到 App_Start 文件夹的 Startup.Auth.cs 文件中

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

      如下:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-10-24
        • 1970-01-01
        • 1970-01-01
        • 2015-07-17
        • 2014-12-19
        • 2013-12-26
        • 1970-01-01
        • 2021-10-12
        相关资源
        最近更新 更多