當我註冊使用以下代碼用戶:MVC - InvalidOperationException異常:用戶ID未找到
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser() { UserName = model.UserName };
IdentityResult result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", "Home");
}
else
{
AddErrors(result);
}
return View(model);
}
}
我能夠訪問所有與[授權]屬性的看法。 不過,如果我註銷,並與我得到
一個錯誤頁面相同的用戶早在「InvalidOperationException異常:用戶ID找不到」
錯誤似乎從我的SignInAsync功能在未來聲明:
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
我不是增加一個用戶名並沒有在用戶班組長(它的ID號),或在AspNetUsers表中沒有用戶ID字段。 用戶存在於該表中,但同樣沒有UserId。
我已經嘗試清除cookie等,但仍然沒有運氣重新登錄。 我在做註冊錯誤嗎?我不明白爲什麼認證正在尋找UserId字段,當它似乎不存在
編輯: 當我第一次登錄時......我得到錯誤頁面。但是,當我重新打開頁面並讀取cookie時,我可以訪問所有內容。初次登錄時發生了什麼?
這裏是SignInAsync方法:
private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var _identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, _identity);
}
列入:
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
你能分享你的用戶模型嗎? – Neshta
用戶是IPrinicipal實現。我認爲它的烘烤英寸和用戶對象是一個IdentityUser – rigamonk
你可以告訴我們的方法SignInAsync(用戶,isPersistent:false)的實現;?添加了 –