当我注册使用以下代码用户: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)的实现;?添加了 –