我仍在努力嘗試使用Identity 2工作來獲取示例應用程序。在接下來的文章中,我得到了幫助將角色信息添加到ViewModel以顯示我的用戶。 Need understanding on how to get/display User RoleASP.Net Identity .FindIdAsync找不到用戶?
現在我試圖解決我點擊用戶的編輯按鈕時遇到的問題。當我嘗試使用.FindIdAsync方法找到它時,我的控制器一直爲用戶提供NULL。但是,在調試模式下,我可以看到正在傳入Edit ActionResult的正確ID。
我在索引視圖中使用ViewModel的事實與它有什麼關係?我會認爲,由於正確傳遞了ID,所以ViewModel將在此時出現。
我在網上搜索,但找不到任何東西來幫助我找出問題。
這是ActionResult,在調試中我可以看到正在填充正確值的id。所以,我不知道爲什麼它沒有找到記錄。沒有錯誤消息,它只是爲用戶對象返回一個NULL,該用戶對象對我表中的每個用戶都顯示「用戶未找到」錯誤。
我希望有人能幫我指點一些東西,我可以看看幫助弄清楚這一點。
public async Task<ActionResult> Edit(string id)
{
AppUser user = await UserManager.FindByIdAsync(id);
if (user != null)
{
return View(user);
}
else
{
return View("Error", new string[] { "User Not Found" });
}
}
public class AppUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
這是我使用索引視圖,我也不會想到會有什麼關係這個問題,但只顯示在情況下,它的視圖模型。
public class UserEditVM : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string UserRole { get; set; }
public IEnumerable<AppRole> AllRoles { get; set; }
}
這裏是我的AppUserManager
public class AppUserManager : UserManager<AppUser>
{
public AppUserManager(IUserStore<AppUser> store)
: base(store)
{
}
public static AppUserManager Create(
IdentityFactoryOptions<AppUserManager> options,
IOwinContext context)
{
AppIdentityDbContext db = context.Get<AppIdentityDbContext>();
AppUserManager manager = new AppUserManager(new UserStore<AppUser>(db));
manager.PasswordValidator = new CustomPasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = false,
RequireDigit = false,
RequireLowercase = true,
RequireUppercase = true
};
manager.UserValidator = new CustomUserValidator(manager)
{
AllowOnlyAlphanumericUserNames = true,
RequireUniqueEmail = true
};
return manager;
}
}
UPDATE:這裏是我的更新視圖模型。刪除了繼承並添加了我從IdentityUser所需的屬性。
public class UserEditVM
{
public string Id { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string UserRole { get; set; }
public IEnumerable<AppRole> AllRoles { get; set; }
}
您的視圖模式真的不應該從IdentityUser繼承,你可能最終會承受過度的攻擊。您應該有一個對象將您的值映射到純粹用於視圖的對象,並且只包含在視圖上顯示所需的字段。我懷疑你需要在視圖上顯示PasswordHash嗎? – Luke
如果您在使用用戶管理器之前將新用戶添加到數據庫上,那麼您是否確實連接到了正確的數據庫?是否將其添加到正確的數據庫? – Luke
移除IdentityUser繼承的良好調用。一旦我做到了,它似乎已經奏效。我不明白爲什麼,雖然理論上這些屬性都可用於我的ViewModel類...雖然有很多額外的屬性,我真的不需要。我更新以顯示新的視圖模型。 – Caverman