【问题标题】:ApplicationUserManager - UserManager throwing exception on creating new userApplicationUserManager - UserManager 在创建新用户时抛出异常
【发布时间】:2018-07-16 02:41:09
【问题描述】:

我正在使用默认的 ASP.net 'Register' 方法从另一个控制器创建新用户:

    public async Task<ActionResult> SyncNewUsers()
    {
            RegisterViewModel register = new RegisterViewModel();
            register.UserName = item.entity_name;
            register.Email = item.fields.preferred_email;
            register.MobilePhone = item.fields.preferred_phone;
            register.Password = "IT@test123";
            register.ConfirmPassword = "IT@test123";
            register.Role = "Admin";
                await new AccountController().RegisterNewUser(register);

            return View();
    }

我的“注册”方法:

        public async Task<ActionResult> RegisterNewUser(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser { UserName = model.UserName, Email = model.Email, PhoneNumber = model.MobilePhone };

            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await this.UserManager.AddToRoleAsync(user.Id, model.Role);

                await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
                AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);



                return RedirectToAction("newxpusers", "Users");
            }
            AddErrors(result);
        }

        return View(model);
    }

但是,它永远不会超过var result = await UserManager.CreateAsync(user, model.Password); 我得到错误的地方:'UserManager' 抛出了类型为 'system.nullreferenceexception' 的异常

我认为它与 UserManager 中的 HttpContext 有关,但是当我将模型动态传递给此方法而不是通过标准表单提交时,我不确定如何处理这个问题。

【问题讨论】:

  • 你为什么要这样做?我的意思是在控制器中创建硬代码用户?我正在像 this 一样将数据播种到 db
  • 我不是对用户进行硬编码,top/first 方法从 API 调用中获取其用户详细信息,因此不需要用户输入。
  • 我可以知道为什么你必须创建像 SyncNewUsers 这样的用户吗?
  • 因为API调用会自动从另一个系统获取新用户,所以我希望用户帐户同时创建。
  • 那你为什么不像我推荐的那样先把用户播种到数据库中呢?

标签: asp.net asp.net-mvc


【解决方案1】:

最终绕过UserManager.CreateAsync(user, model.Password);,实现以下:

var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var result = await manager.CreateAsync(user, model.Password);

【讨论】:

    【解决方案2】:

    我知道我可能迟到了,但为了后人的缘故。我有同样的错误,我意识到这毕竟是密码要求。确保:

    1. 它包含一个数字

    2. 它包含一个特殊字符

    3. 长度为 8 个字符

    完成此操作后,记录已插入数据库,因此我建议您在发送表单之前设置或检查密码要求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-17
      • 1970-01-01
      • 2020-10-21
      • 2014-10-28
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多