如何解决尝试将新用户从appsettings.json文件添加到Azure存储表中
运行代码时出现空引用异常。
我创建了两个块来从appsettings.json中读取用户电子邮件,并使用种子方法将其保存为Azure存储。它仅适用于添加管理员角色。但是每次创建第二个角色时,它都会引发System.ArgumentNullException。
//Works fine
var admin = await userManager.FindByEmailAsync(options.Value.AdminEmail);
if (admin == null)
{
ApplicationUser user = new ApplicationUser
{
UserName = options.Value.AdminName,Email = options.Value.AdminEmail,EmailConfirmed = true
};
IdentityResult result = await userManager.CreateAsync(user,options.Value.AdminPassword);
await userManager.AddClaimAsync(user,new System.Security.Claims.Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress",options.Value.AdminEmail));
await userManager.AddClaimAsync(user,new System.Security.Claims.Claim("IsActive","True"));
// Add Admin to Admin roles
if (result.Succeeded)
{
await userManager.AddToRoleAsync(user,Roles.Admin.ToString());
}
}
//System.ArgumentNullException: 'Value cannot be null.'
var engineer = await userManager.FindByEmailAsync(options.Value.EngineerEmail);
if (engineer == null)
{
ApplicationUser user = new ApplicationUser
{
UserName = options.Value.EngineerName,Email = options.Value.EngineerEmail,EmailConfirmed = true,LockoutEnabled = false
};
IdentityResult result = await userManager.CreateAsync(user,options.Value.EngineerPassword);
await userManager.AddClaimAsync(user,options.Value.EngineerEmail));
await userManager.AddClaimAsync(user,"True"));
// Add Service Engineer to Engineer role
if (result.Succeeded)
{
await userManager.AddToRoleAsync(user,Roles.Engineer.ToString());
}
}
解决方法
每次创建第二个角色时都会抛出NullReferenceException
//System.ArgumentNullException: 'Value cannot be null.'
var engineer = await userManager.FindByEmailAsync(options.Value.EngineerEmail);
如果userManager.FindByEmailAsync(options.Value.EngineerEmail)
为options.Value.EngineerEmail
,则此代码段null
将引发异常。
异常
我使用以下代码段和json数据进行了测试,它们可以正常工作。请检查您的
MyConfigOptions类
public class MyConfigOptions
{
public string AdminEmail { get; set; }
public string AdminName { get; set; }
public string AdminPassword { get; set; }
public string EngineerEmail { get; set; }
public string EngineerName { get; set; }
public string EngineerPassword { get; set; }
}
appsettings.json
"ConfigOfUsers": {
"AdminName": "admin","AdminEmail": "admin@example.com","AdminPassword": "Test123456789","EngineerEmail": "user1@example.com","EngineerName": "user1","EngineerPassword": "Test123456789"
}
将MyConfigOptions类绑定到ConfigOfUsers部分
services.AddOptions<MyConfigOptions>()
.Bind(Configuration.GetSection("ConfigOfUsers"))
.ValidateDataAnnotations();
测试结果
此外,您可以参考this doc about "options pattern in ASP.NET Core"并检查与选项模式相关的配置和json数据格式等是否正确设置。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。