我正在尝试在Identity 2.1中异步设置/重置大量用户密码。当我运行该过程时,它似乎与ApplicationUserManager混淆。 (例如,即使我将新的ID和密码传递给新线程,我也会收到一条错误消息,说明当用户未完成上一个用户时,它正在尝试更改用户。)由于当前上下文不在新线程,我正在将ApplicationUserManager传递给执行实际重置的过程。当我按照所示(同步)运行它时,它工作正常,但每个用户需要2-3秒。这意味着运行8-10个小时。 如果我可以在ProcessUser例程中实例化ApplicationUserManager,我认为问题会消失,但到目前为止我还没有能够,因为没有与页面相关的上下文。 任何修复?
Private Sub ProcessUsers()
Dim mgr = Context.GetOwinContext().GetUserManager(Of ApplicationUserManager)() ' As New ApplicationUserManager()
Dim ctx As New BCRContext()
Dim ttl As Integer = 0
Dim status As String
' Turn off password requirements for these temp passwords.
mgr.PasswordValidator = New PasswordValidator() With {
.RequireDigit = False,
.RequireLowercase = False,
.RequiredLength = 4,
.RequireUppercase = False,
.RequireNonLetterOrDigit = False
}
' Get the list of user ID's and temp passswords
Dim qry As List(Of MyStuffDTO) = ctx.Database.SqlQuery(Of MyStuffDTO)("SELECT tmpPass.ID, Pass FROM tmpPass INNER JOIN AspNetUsers U ON U.ID=tmpPass.ID WHERE U.PasswordHash IS NULL ").ToList()
Try
For Each guy As MyStuffDTO In qry
ttl += 1
status = ttl & "/" & qry.Count & " - "
ProcessUser(guy, mgr, status)
'Dim task__1 = Task(Of String).Factory.StartNew(Function()
' Return ProcessUser(guy, mgr, status)
' End Function
' )
Next
Debug.WriteLine("Done assigning tasks")
Catch ex As Exception
Logger.Error("Error processing guys", ex)
End Try
End Sub
Private Function ProcessUser(guy As MyStuffDTO, mgr As ApplicationUserManager, status As String) As String
Dim rslt As IdentityResult = Nothing
Dim msg As String = ""
Try
If mgr.HasPassword(guy.ID) Then
rslt = mgr.RemovePassword(guy.ID)
If Not rslt.Succeeded Then
msg = status & "Error removing password for ID:" & guy.ID & " - " & rslt.Errors(0)
Debug.WriteLine(msg)
Logger.Warn(msg)
Return msg
End If
End If
rslt = mgr.AddPassword(guy.ID, guy.Pass)
If Not rslt.Succeeded Then
msg = status & "Error setting password for ID:" & guy.ID & " - " & rslt.Errors(0)
Debug.WriteLine(msg)
Logger.Warn(msg)
Else
msg = status & "Succeeded for ID:" & guy.ID
Debug.WriteLine(msg)
End If
Catch ex As Exception
msg = "Error progessing guy " & guy.ID
Logger.Error("Error progessing guy " & guy.ID, ex)
Return msg & " - " & ex.Message
End Try
Return msg
End Function
Public Class MyStuffDTO
Public Property ID As String
Public Property Pass As String
End Class
答案 0 :(得分:0)
我的VB有点粗糙所以我会在C#中发布我的例子
从OwinContext获取UserManager后,您可以像这样循环用户......
var user = await UserManager.FindByNameAsync(model.Email);
UserManager.GeneratePasswordResetTokenAsync(user.Id).ContinueWith((t) => { UserManager.ResetPasswordAsync(user.Id, t.Result, "NEW PASSWORD"); });