身份2.1 - 未找到UserId但之前正在使用

时间:2021-12-23 16:55:20

This code worked before numerous times but after adding in a couple new properties for a user in Identity 2.1 it has ceased to work suddenly. I am getting a UserId not found error, despite there being a value visible in the debugger for UserId. Anyone have an idea on why this has suddenly happened? It's very frustrating to see the least.

此代码在很多次之前有效,但在为Identity 2.1中的用户添加了几个新属性后,它已经停止工作。我收到UserId未找到错误,尽管在UserId的调试器中可以看到值。任何人都知道为什么会突然发生这种情况?至少看到它是非常令人沮丧的。

Here's code:(Controller)

 // POST: /Account/Register    [HttpPost]    [AllowAnonymous]    [ValidateAntiForgeryToken]    public async Task<ActionResult> Register(RegisterViewModel model)    {        model.BackgroundOnFile = false;        if (ModelState.IsValid)        {            var userDetails = new ApplicationUser { UserName = model.Email, Title = model.Title, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, LEAID = model.LEAID, SchoolID = model.SchoolID, Address1 = model.Address1, Address2 = model.Address2, City = model.City, State = model.State, PostCode = model.PostCode, BackgroundOnFile = model.BackgroundOnFile, BoardStart = model.BoardStart, BoardEnd = model.BoardEnd, PhoneNumber = model.PhoneNumber };            var result = await UserManager.CreateAsync(userDetails, model.Password);            //Assign Role            UserManager.AddToRole(userDetails.Id, "User");            if (result.Succeeded)            {                await SignInManager.SignInAsync(userDetails, isPersistent:false, rememberBrowser:false);                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771                // Send an email with this link                // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);                // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);                // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");                return RedirectToAction("Index", "Home");            }            AddErrors(result);        }        // If we got this far, something failed, redisplay form        return View(model);    }

And the Model:

而型号:

public class ApplicationUser : IdentityUser{    //Extra items required to register    public string Title { get; set; }    public string FirstName { get; set; }    public string LastName { get; set; }    public int LEAID { get; set; }    public int SchoolID { get; set; }    public string Address1 { get; set; }    public string Address2 { get; set; }    public string City { get; set; }    public string State { get; set; }    //Post Code is a string to accomodate future possible Canadian style post codes    public string PostCode { get; set; }    public bool BackgroundOnFile { get; set; }    public System.DateTime BoardStart { get; set; }    public System.DateTime BoardEnd { get; set; }    public string NominatedBy { get; set; }    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;    }}

And the error:

而错误:

UserId not found.Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidOperationException: UserId not found.Source Error: Line 168:                Line 169:                //Assign RoleLine 170:                UserManager.AddToRole(userDetails.Id, "User");Line 171:Line 172:                if (result.Succeeded)Source File: h:\app\Controllers\AccountController.cs    Line: 170 Stack Trace: [InvalidOperationException: UserId not found.]   Microsoft.AspNet.Identity.<AddToRoleAsync>d__83.MoveNext() +871   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52   System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +24   Microsoft.AspNet.Identity.AsyncHelper.RunSync(Func`1 func) +409   Microsoft.AspNet.Identity.UserManagerExtensions.AddToRole(UserManager`2 manager, TKey userId, String role) +260   UCAP.Controllers.<Register>d__7.MoveNext() in h:\Laptop Transfer\Training Code\1\CSMapAlpha3\CSMapAlpha3\Controllers\AccountController.cs:170   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52   System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21   System.Threading.Tasks.TaskHelpersExtensions.ThrowIfFaulted(Task task) +61   System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult) +114   System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeAsynchronousActionMethod>b__36(IAsyncResult asyncResult) +66   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +47   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +136   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +49   System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +117   System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +323   System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +44   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +47   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +136   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +50   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +72   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +185   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44   System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +39   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +39   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9651688   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

3 个解决方案

#1


6  

Having the same error right now!The only relevant recent action I've made is the update of packages through NuGet:

现在有同样的错误!我最近的唯一相关行动是通过NuGet更新包:

  • EntityFramework 6.1.1 to 6.1.3
  • EntityFramework 6.1.1至6.1.3

  • Microsoft ASP.NET IdentityCore 2.1.0to 2.2.1
  • Microsoft ASP.NET IdentityCore 2.1.0到2.2.1

  • Microsoft ASP.NET Identity EntityFramework 2.1.0 to 2.2.1
  • Microsoft ASP.NET Identity EntityFramework 2.1.0到2.2.1

  • Microsoft ASP.NET Identity Owin 2.1.0 to 2.2.1
  • Microsoft ASP.NET Identity Owin 2.1.0到2.2.1

Still investigating anyway...

还在调查......

UPDATE

In my case I was trying to generate the confirmation token before saving the user. I learned that UserManager.GenerateEmailConfirmationTokenAsync(userID) generates the token upon a saved ID, not the one you have in memory.

在我的情况下,我试图在保存用户之前生成确认令牌。我了解到UserManager.GenerateEmailConfirmationTokenAsync(userID)在保存的ID上生成令牌,而不是在内存中生成的令牌。

Hope this helps, somehow.

希望这会有所帮助,不知何故。

#2


3  

This exception is not generated by Application User class, there is no property named UserID in this class. (its Id not UserId)

Application User类不生成此异常,此类中没有名为UserID的属性。 (它的身份不是UserId)

So there are two Tables in Identity database contains column with UserID

因此,Identity数据库中有两个表包含具有UserID的列

  1. IdentityRole
  2. IdentityUserRole

Therefore exception is being raised during insert in these tables, there is nothing wrong with ApplicationUser.Id. Make sure that role with name "User" exists. also check for name case i.e. "User"/"user"

因此,在这些表中插入期间会引发异常,ApplicationUser.Id没有任何问题。确保名称为“User”的角色存在。还检查名称案例,即“用户”/“用户”

#3


1  

If, like me, you struggle to get identity framework working without fully appreciating all the ins and outs, this may help. I was using this line to get a reference to the user:

如果像我一样,你很难在不完全理解所有细节的情况下使身份框架工作,这可能会有所帮助。我正在使用此行来获取对用户的引用:

var user = new ApplicationUser { UserName = ...

This creates a new user. What I should have done is use this line:

这会创建一个新用户。我应该做的是使用这一行:

var user = UserManager.FindByEmail( ...

You can then reset the password like this:

然后,您可以重置密码,如下所示:

string code = UserManager.GeneratePasswordResetToken(user.Id);var result = UserManager.ResetPassword(user.Id, code, model.Password);

Note that this has no error-checking.

请注意,这没有错误检查。

#1


6  

Having the same error right now!The only relevant recent action I've made is the update of packages through NuGet:

现在有同样的错误!我最近的唯一相关行动是通过NuGet更新包:

  • EntityFramework 6.1.1 to 6.1.3
  • EntityFramework 6.1.1至6.1.3

  • Microsoft ASP.NET IdentityCore 2.1.0to 2.2.1
  • Microsoft ASP.NET IdentityCore 2.1.0到2.2.1

  • Microsoft ASP.NET Identity EntityFramework 2.1.0 to 2.2.1
  • Microsoft ASP.NET Identity EntityFramework 2.1.0到2.2.1

  • Microsoft ASP.NET Identity Owin 2.1.0 to 2.2.1
  • Microsoft ASP.NET Identity Owin 2.1.0到2.2.1

Still investigating anyway...

还在调查......

UPDATE

In my case I was trying to generate the confirmation token before saving the user. I learned that UserManager.GenerateEmailConfirmationTokenAsync(userID) generates the token upon a saved ID, not the one you have in memory.

在我的情况下,我试图在保存用户之前生成确认令牌。我了解到UserManager.GenerateEmailConfirmationTokenAsync(userID)在保存的ID上生成令牌,而不是在内存中生成的令牌。

Hope this helps, somehow.

希望这会有所帮助,不知何故。

#2


3  

This exception is not generated by Application User class, there is no property named UserID in this class. (its Id not UserId)

Application User类不生成此异常,此类中没有名为UserID的属性。 (它的身份不是UserId)

So there are two Tables in Identity database contains column with UserID

因此,Identity数据库中有两个表包含具有UserID的列

  1. IdentityRole
  2. IdentityUserRole

Therefore exception is being raised during insert in these tables, there is nothing wrong with ApplicationUser.Id. Make sure that role with name "User" exists. also check for name case i.e. "User"/"user"

因此,在这些表中插入期间会引发异常,ApplicationUser.Id没有任何问题。确保名称为“User”的角色存在。还检查名称案例,即“用户”/“用户”

#3


1  

If, like me, you struggle to get identity framework working without fully appreciating all the ins and outs, this may help. I was using this line to get a reference to the user:

如果像我一样,你很难在不完全理解所有细节的情况下使身份框架工作,这可能会有所帮助。我正在使用此行来获取对用户的引用:

var user = new ApplicationUser { UserName = ...

This creates a new user. What I should have done is use this line:

这会创建一个新用户。我应该做的是使用这一行:

var user = UserManager.FindByEmail( ...

You can then reset the password like this:

然后,您可以重置密码,如下所示:

string code = UserManager.GeneratePasswordResetToken(user.Id);var result = UserManager.ResetPassword(user.Id, code, model.Password);

Note that this has no error-checking.

请注意,这没有错误检查。