我一直在试验 MVC5/EF6 并尝试使用代码优先迁移进行新的身份验证。解决方案中的所有内容目前都在构建,我可以添加 Migration
,但是当我通过 VS2013 中的 update-database
执行 package manager console
时,我的 Configuration.cs
文件无法将我的测试数据完全处理到我的表中并输出 Error Adding User to Role: UserId not found
。
我曾尝试明确设置一个用户 ID 并将其留给管理器生成(如某些示例所示),但每次我都收到相同的错误消息。我知道错误在我的 #region User & User Roles
文件的 Configuration.cs
中失败了,但我不确定为什么:
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using PersonalPortfolio2.Helper;
using PersonalPortfolio2.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Diagnostics;
using System.Linq;
namespace PersonalPortfolio2.Models
{
public sealed class Configuration : DbMigrationsConfiguration<PersonalPortfolio2.Models.ApplicationDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(PersonalPortfolio2.Models.ApplicationDbContext context)
{
BlobHelper bh = new BlobHelper();
//LocationHelper lh = new LocationHelper();
ApplicationDbContext db = new ApplicationDbContext();
#region Roles
try
{
List<string> myRoles = new List<string>(new string[] { "Root", "Admin", "Outsider", "Client", "Primary" });
var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
foreach (string r in myRoles)
{
RoleManager.Create(new IdentityRole(r));
}
}
catch (Exception ex)
{
throw new Exception("Error Create Roles: " + ex.Message);
}
#endregion
#region User & User Roles
var store = new UserStore<ApplicationUser>(context);
var manager = new UserManager<ApplicationUser>(store);
List<ApplicationUser> myUsers = GetTestUsers();
var passwordHasher = new PasswordHasher();
foreach (var u in myUsers)
{
var userExists = db.Users.Where(a => a.Email == u.Email).FirstOrDefault();
if (userExists == null)
{
var user = new ApplicationUser
{
Email = u.Email,
PasswordHash = passwordHasher.HashPassword("P@ssword1"),
LockoutEnabled = false,
Name = u.Name,
Position = u.Position,
RegisteredDate = DateTime.Now,
LastVisitDate = DateTime.Now,
OrganizationId = u.OrganizationId,
ProfilePictureSrc = u.ProfilePictureSrc,
};
try
{
var userCreateResult = manager.Create(user);
}
catch (Exception ex)
{
throw new Exception("Error Add User: " + ex.Message + "\n" + ex.InnerException);
}
// Add User to Roles
List<string> usersRoles = GetUserRoles(u.Email);
bool codeHit = false;
foreach (string role in usersRoles)
{
try
{
codeHit = true;
manager.AddToRole(user.Id, role);
}
catch (Exception ex)
{
// ERROR!
throw new Exception("Error Adding User to Role: " + ex.Message + "\n" + ex.Data + "\n" + ex.InnerException + "\nName: " + user.Name + "\nEmail: " + user.Email + "\nuser.ID: " + user.Id + "\nu.Id: " + u.Id + "\nRole: " + role + "\nCodeHit: " + codeHit);
}
}
}
}
#endregion
}
#region Helpers
private List<ApplicationUser> GetTestUsers()
{
List<ApplicationUser> testUsers = new List<ApplicationUser>
{
new ApplicationUser
{
Id = "1",
Email = "Admin@abc.com",
Name = "Admin User",
RegisteredDate = System.DateTime.Now,
LastVisitDate = System.DateTime.Now,
Position = "Site Administrator",
PhoneNumber = "1234564321",
},
new ApplicationUser
{
Id = "2",
Email = "first.last@hotmail.com",
Name = "James Woods",
RegisteredDate = System.DateTime.Now,
LastVisitDate = System.DateTime.Now,
Position = "Software Developer / Web Designer",
PhoneNumber = "1234567890",
},
new ApplicationUser
{
Id = "3",
Email = "tyler.perry@gmail.com",
Name = "Tyler Perry",
RegisteredDate = System.DateTime.Now,
LastVisitDate = System.DateTime.Now,
Position = "Company Contact",
PhoneNumber = "1234567890",
}
};
return testUsers;
}
public List<string> GetUserRoles(string user)
{
List<string> myRoles = new List<string>();
switch (user)
{
//"Root", "Admin", "Outsider", "Client", "Primary"
case "Admin@abc.com":
myRoles = new List<string>(new string[] { "Root", "Admin" });
break;
case "first.last@hotmail.com":
myRoles = new List<string>(new string[] { "Admin" });
break;
case "tyler.perry@gmail.com":
myRoles = new List<string>(new string[] { "Client", "Outsider" });
break;
default:
myRoles = new List<string>(new string[] {"[user] not found."});
break;
}
return myRoles;
}
#endregion
}
}
任何人都可以在这里提供一些我可能忽略的见解吗?有关详细信息,我当前的 catch
语句输出以下内容:
Error Adding User to Role: UserId not found.
System.Collections.ListDictionaryInternal
Name: Admin User
Email: Admin@abc.com
user.ID: 1
u.Id: 1
Role: Root
CodeHit: True
当我为管理员用户注释掉显式 Id = "1",
时,user.ID
和 u.Id
变为: ab753316-3d7b-4f98-a13a-d19f7c926976
。我原以为问题可能出在我的 GetTestUsers()
或 GetUserRoles(u.Email)
辅助方法上,但在我的 try/catch
和我正在使用的 codeHit
bool 变量之间,我已经验证问题肯定来自 manager.AddToRole(user.Id, role)
。
最佳答案
我将此留给可能有类似问题的任何人。我有完全相同的“症状”。事实证明,问题与存储的密码不符合配置的密码策略(至少一个大写字符、一个小写字符等)有关。
根据下面的评论和答案,一般来说,如果不遵守任何用户创建约束或策略,则会抛出相同的模糊错误消息。
这可能包括以下内容:
- 未遵守密码政策(这似乎是最常见的原因)
- 必填字段作为空字符串/null 传递
- 重复的用户名或电子邮件
确实有很多问题会导致此错误发生。如果以上不能解决您的问题,我建议如下:
- 熟悉为您的解决方案设置的 identityprovider 的规则和政策
- 按照下面@Ted 的回答,跟踪或在 UserManager.Create 方法上设置断点以查看结果,因为这可能会揭示问题的原因。
关于c# - MVC5 : UserManager. 添加到角色 () : "Error Adding User to Role: UserId not found"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24389126/