出于某种原因,在我的种子类中使用时,'Identity'的'UserManager'不会存储新用户。播种类中的其他所有内容都可以正常工作,只是'CreateAsync'方法问题。这是代码:
public class WorldContextSeedData
{
private WorldContext _context;
private UserManager<WorldUser> _userManager;
public WorldContextSeedData(WorldContext context, UserManager<WorldUser> userManager)
{
_context = context;
_userManager = userManager;
}
public async Task EnsureSeedData()
{
if (await _userManager.FindByEmailAsync("lucas@test.com") == null)
{
//add user
var newUser = new WorldUser
{
UserName = "Lucas",
Email = "lucas@test.com"
};
await _userManager.CreateAsync(newUser, "MyP@ssword!");
}
if (!_context.Trips.Any())
{
//Add new Data
var usTrip = new Trip()
{
Name = "US Trip",
CreatedBy = "Lucas",
Timestamp = DateTime.Now,
Stops = new List<Stop>()
{
new Stop { Name= "Atlanta, GA", Order = 0},
new Stop { Name= "NYC, NY", Order = 1},
new Stop { Name= "Tempe, AZ", Order = 2}
}
};
var worldTrip = new Trip()
{
Name = "World Trip",
CreatedBy = "Lucas",
Timestamp = DateTime.Now,
Stops = new List<Stop>()
{
new Stop { Name= "Poland", Order = 0},
new Stop { Name= "France", Order = 1},
new Stop { Name= "Germany", Order = 2}
}
};
_context.Trips.Add(usTrip);
_context.Stops.AddRange(usTrip.Stops);
_context.Trips.Add(worldTrip);
_context.Stops.AddRange(worldTrip.Stops);
_context.SaveChanges();
}
}
}
答案 0 :(得分:2)
根据史蒂夫的精彩评论提示,我能够验证密码太弱了。一旦我使密码更强(需要数字),问题就解决了。
在这里,我介绍了一个包含创建新用户的返回结果的变量:
IdentityResult result = await _userManager.CreateAsync(newUser, newUserPassword);
答案 1 :(得分:0)
您可以使用
IdentityResult result = await _userManager.CreateAsync(newUser, "MyP@ssword!");
查看结果是什么问题。 IdentityResult包含bool成功确定创建如何进行。并包含Errors属性以向您显示出了什么问题。
答案 2 :(得分:0)
将以下代码行添加到IdentityHostingStartup.cs:
services.Configure<IdentityOptions>(x => {
x.Password.RequireDigit = false;
x.Password.RequiredLength = 2;
x.Password.RequireUppercase = false;
x.Password.RequireLowercase = false;
x.Password.RequireNonAlphanumeric = false;
x.Password.RequiredUniqueChars = 0;
x.Lockout.AllowedForNewUsers = true;
x.Lockout.MaxFailedAccessAttempts = 5;
x.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromSeconds(30);
});