【问题标题】:Create user programmatically using C# ASP.NET MVC Identity使用 C# ASP.NET MVC Identity 以编程方式创建用户
【发布时间】:2019-07-07 03:43:34
【问题描述】:

我正在尝试以编程方式将用户添加到 ASP.NET MVC 身份。

我遇到的错误是:UserManager threw an exception of type 'System.NullReferenceException'

这个函数是通过一个不是来自这个站点的 POST 调用的。它位于 AccountController 中 public async Task<ActionResult> Register(RegisterViewModel model) 的正下方。

[AllowAnonymous]
public async Task<bool> GenerateUser(string email)
{
        var user = new ApplicationUser { UserName = email, Email = email };
        string password = System.Web.Security.Membership.GeneratePassword(12, 4);
        var result = await UserManager.CreateAsync(user, password);

        if (result.Succeeded)
        {
           // Omitted
        }
        else { AddErrors(result); }

        return true;
 }

我也尝试使用下面的代码来执行相同的操作,但是我收到了错误,即用户名中不能有特殊字符(我使用的是电子邮件地址),但这绝对是允许的,因为它就是这样我所有的用户都是使用public async Task&lt;ActionResult&gt; Register(RegisterViewModel model) 创建的。

string password = System.Web.Security.Membership.GeneratePassword(12, 4);
var store = new Microsoft.AspNet.Identity.EntityFramework.UserStore<ApplicationUser>();
var manager = new ApplicationUserManager(store);
var user = new ApplicationUser() { Email = email, UserName = email };
var result = manager.Create(user, password);

用户对象与我填写表单以在站点上创建新用户一样(使用public async Task&lt;ActionResult&gt; Register(RegisterViewModel model)),密码只是一个字符串,也一样。


public async Task&lt;ActionResult&gt; Register(RegisterViewModel model) 是根据脚手架的默认设置,但无论如何都在下面供参考:

// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                //await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

                // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                 string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                 var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                 await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                //return RedirectToAction("Index", "Home");
                // TODO: Email Sent
                return View("ConfirmationSent");
            }
            AddErrors(result);
        }

        // If we got this far, something failed, redisplay form
        return View(model);
 }

编辑:

我调用函数:

var result = new AccountController().GenerateUser(model.emailAddress);

编辑2:

如要求:这是ApplicationUserManager 的类定义

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
    {
        var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
        // Configure validation logic for usernames
        manager.UserValidator = new UserValidator<ApplicationUser>(manager)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };

        // Configure validation logic for passwords
        manager.PasswordValidator = new PasswordValidator
        {
            RequiredLength = 8,
            RequireNonLetterOrDigit = false,
            RequireDigit = false,
            RequireLowercase = false,
            RequireUppercase = false,
        };

        // Configure user lockout defaults
        manager.UserLockoutEnabledByDefault = true;
        manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
        manager.MaxFailedAccessAttemptsBeforeLockout = 5;

        // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
        // You can write your own provider and plug it in here.
        manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
        {
            MessageFormat = "Your security code is {0}"
        });
        manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
        {
            Subject = "Security Code",
            BodyFormat = "Your security code is {0}"
        });
        manager.EmailService = new EmailService();
        manager.SmsService = new SmsService();
        var dataProtectionProvider = options.DataProtectionProvider;
        if (dataProtectionProvider != null)
        {
            manager.UserTokenProvider = 
                new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
        }
        return manager;
    }
}

【问题讨论】:

  • 你的错误在哪里?
  • @Cid 来自第一个代码块第6行的'result' var。
  • 由于您使用的是ApplicationUserManager构造函数,您之前是否尝试过设置UserValidator?我认为您应该在这种情况下设置AllowOnlyAlphanumericUserNames = false,您能否在问题中显示ApplicationUserManager 类定义?
  • @TetsuyaYamamoto 这给了我一个新的错误,但我们似乎得到了某个地方。我现在得到The entity type ApplicationUser is not part of the model for the current context.。我用manager.UserValidator = new UserValidator&lt;ApplicationUser&gt;(manager) { AllowOnlyAlphanumericUserNames = false, RequireUniqueEmail = true }; 设置它我还创建了PasswordValidator

标签: c# asp.net asp.net-mvc asp.net-web-api asp.net-mvc-5


【解决方案1】:

问题出在 UserManager 上,这解决了问题。

    ApplicationDbContext context = new ApplicationDbContext();

    var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
    var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
    UserManager.UserValidator = new UserValidator<ApplicationUser>(UserManager)
    {
        AllowOnlyAlphanumericUserNames = false,
        RequireUniqueEmail = true
    };

    string password = System.Web.Security.Membership.GeneratePassword(12, 4);
    var user = new ApplicationUser();
    user.Email = model.Email;
    user.UserName = model.Email;

    string userPWD = password;

    var result = UserManager.Create(user, userPWD);

【讨论】:

    猜你喜欢
    • 2017-01-12
    • 2014-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多