在注册表单之外创建身份用户会导致NullReferenceException

问题描述 投票:0回答:1

我有一个Hangfire作业,尝试基于旧数据库创建身份用户。不幸的是,它导致此错误(来自Hangfire):

Failed to process the job '24': an exception occurred. Retry attempt 6 of 10 will be performed in 00:12:04.
System.NullReferenceException: Object reference not set to an instance of an object.
   at userpanel.BatchRegistration.CreateUser(String providedEmail, String providedPassword, String providedTraccarId, Nullable\`1 providedIsAdmin) in C:\Users\Vostro2017\source\repos\userpanel\Jobs.cs:line 83
   at userpanel.Jobs.UpdateUsers() in C:\...\userpanel\Jobs.cs:line 40
   at userpanel.Jobs.UpdateUsers() in C:\...\userpanel\Jobs.cs:line 42
   at userpanel.Jobs.UpdateUsers() in C:\...\userpanel\Jobs.cs:line 42
   at userpanel.Jobs.UpdateUsers() in C:\...\userpanel\Jobs.cs:line 44
   at System.Runtime.CompilerServices.TaskAwaiter\`1.GetResult()

我希望它改为创建用户。

Jobs.cs

namespace userpanel {
    public class Jobs {
        public static async Task<bool> UpdateUsers() {
            await using var conn = new NpgsqlConnection("Server=localhost;Port=5432;Database=Old;Username=postgres;Password=123456");
            await conn.OpenAsync();

            //
            // 1. Download old users and create Identity versions
            //
            await using (var cmd = new NpgsqlCommand("SELECT * FROM public.old_users ORDER BY id;", conn))
            await using (var reader = await cmd.ExecuteReaderAsync()) {
                while (await reader.ReadAsync()) {
                    string providedOldId = reader.GetInt32(0).ToString();
                    string providedEmail = reader.GetString(2);
                    bool? providedIsAdmin = reader.GetBoolean(6);
                    string providedPassword = "123456";
                    await BatchRegistration.CreateUser(providedEmail, providedPassword, providedOldId, providedIsAdmin);
                }
            }
            await conn.CloseAsync();
            return true;
        }
    }

    public class BatchRegistration : PageModel {
        public static SignInManager<ApplicationUser> _signInManager;
        public static UserManager<ApplicationUser> _userManager;
        public static ILogger<RegisterModel> _logger;

        public BatchRegistration(
            UserManager<ApplicationUser> userManager,
            SignInManager<ApplicationUser> signInManager,
            ILogger<RegisterModel> logger) {
            _userManager = userManager;
            _signInManager = signInManager;
            _logger = logger;
        }

        public static async Task CreateUser(string providedEmail, string providedPassword, string providedOldId, bool? providedIsAdmin) {
            bool IsAdmin = providedIsAdmin.HasValue != false;
            var user = new ApplicationUser {
                UserName = providedEmail,
                Email = providedEmail,
                EmailConfirmed = true,
                UserOldEmail = providedEmail,
                UserOldId = providedOldId,
                IsPaymentRequired = true,
                IsAdministrator = IsAdmin,
                Currency = 0.00
                };
            foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(user)) {
                string name = descriptor.Name;
                object value = descriptor.GetValue(user);
                Console.WriteLine("{0}={1}", name, value);
            }
            await _userManager.CreateAsync(user, providedPassword);
        }
    }
}

我的模特:

public class ApplicationUser : IdentityUser {
    public string UserOldId { get; set; } // actually int, wouldn't let me migrate
    public string UserOldEmail { get; set; } 
    public bool IsPaymentRequired { get; set; }
    public bool IsAdministrator { get; set; }
    public double Currency { get; set; }
    public ICollection<UserDevice> Devices { get; } = new List<UserDevice>();
}

我找不到找到这样的用户的方法,所以我只复制了注册表单后端,并根据需要对其进行了修改。

我已经尝试用new ApplicationUser数据填充我的IdentityUser,但是没有用。我还检查了是否有任何条目为空/空-一切似乎都很好。

我不认为它类似于this question-我知道此异常的含义,但是我对ASP.NET完全是绿色的,并且我认为它与以某种方式绑定到UserManager有关,因为所有数据都提供给_userManager.CreateAsync有效。

Edit-我在Startup.cs方法的末尾在Configure中添加我的Hangfire作业,如下所示:

BackgroundJob.Enqueue(() => Jobs.UpdateUsers());
c# asp.net-core-mvc hangfire
1个回答
0
投票

我意识到我做了整个事情,却不了解我要做什么。根据jbl的建议,我将Jobs.cs更改为:

namespace userpanel {
    public class Jobs : PageModel {

        public UserManager<ApplicationUser> _userManager;

        public Jobs(UserManager<ApplicationUser> userManager) {
            _userManager = userManager;
        }

        public async Task<bool> UpdateUsers() {
            await using var conn = new NpgsqlConnection("Server=localhost;Port=5432;Database=Old;Username=postgres;Password=123456");
            await conn.OpenAsync();

            //
            // 1. Download old users and create Identity versions
            //
            await using (var cmd = new NpgsqlCommand("SELECT * FROM public.old_users ORDER BY id;", conn))
            await using (var reader = await cmd.ExecuteReaderAsync()) {
                while (await reader.ReadAsync()) {
                    string providedOldId = reader.GetInt32(0).ToString();
                    string providedEmail = reader.GetString(2);
                    bool? providedIsAdmin = reader.GetBoolean(6);
                    string providedPassword = "123456";
                    await CreateUser(providedEmail, providedPassword, providedOldId, providedIsAdmin);
                }
            }
            await conn.CloseAsync();
            return true;

            // ...
        }

        public async Task CreateUser(string providedEmail, string providedPassword, string providedOldId, bool?     providedIsAdmin) {
            bool IsAdmin = providedIsAdmin.HasValue != false;
            var user = new ApplicationUser {
                UserName = providedEmail,
                Email = providedEmail,
                EmailConfirmed = true,
                UserOldEmail = providedEmail,
                UserOldId = providedOldId,
                IsPaymentRequired = true,
                IsAdministrator = IsAdmin,
                Currency = 0.00
                };
            await _userManager.CreateAsync(user, providedPassword);
        }
    }
}

现在我的Hangfire作业也使用此行执行:

BackgroundJob.Enqueue<Jobs>(j => j.UpdateUsers());
© www.soinside.com 2019 - 2024. All rights reserved.