2017-05-12 31 views
0

我在其中一個項目中使用了MVC身份。在註冊用戶後,我不斷收到以下錯誤:以MVC身份發送郵件時出現異步問題

「異步模塊或處理程序在異步 操作仍未完成時完成」。

我在我的控制器中實現了Await,無法看到我要出錯的地方,如果有人可以請指教。非常感謝。

控制器:

<HttpPost> 
    <AllowAnonymous> 
    <ValidateAntiForgeryToken> 
    Public Async Function Register(model As RegisterViewModel) As Task(Of ActionResult) 
     If ModelState.IsValid Then 
      Dim user = New ApplicationUser() With { 
      .UserName = model.Email, 
      .Email = model.Email, 
      .FullName = model.FullName, 
      .UserSettings = New UserSettings() With { 
      .OrderEnabled1 = True, .OrderEnabled2 = True, .OrderEnabled3 = True, .OrderEnabled4 = True, .OrderEnabled5 = True, .OrderEnabled6 = True, .OrderEnabled7 = True, 
      .OrderInput1 = 1, .OrderInput2 = 2, .OrderInput3 = 3, .OrderInput4 = 4, .OrderInput5 = 5, .OrderInput6 = 6, .OrderInput7 = 7, 
      .VAT = VATconst 
      } 
     } 

      user.UserSettings.Id = user.Id 

      Dim result = Await UserManager.CreateAsync(user) 

      If result.Succeeded Then 
       UserManager.AddToRole(user.Id, "User") 

       Dim code = Await UserManager.GenerateEmailConfirmationTokenAsync(user.Id) 
       Dim callbackUrl = Url.Action("ConfirmEmail", "Account", New With {.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", "Users") 

      End If 
      AddErrors(result) 
     End If 

     Return View(model) 
    End Function 

電子郵件服務:

Public Class EmailService 
Implements IIdentityMessageService 

Public Function SendAsync(message As IdentityMessage) As Task Implements IIdentityMessageService.SendAsync 
    ' Plug in your email service here to send an email. 

    ' Create the mail message 
    Dim msg As New MailMessage() 
    msg.To.Add(message.Destination) 

    Dim address As New MailAddress("*****@gmail.com") 
    msg.From = address 
    msg.Subject = message.Subject 
    msg.Body = message.Body 
    msg.IsBodyHtml = True 

    'Configure an SmtpClient to send the mail.    
    Dim client As New SmtpClient() 
    client.DeliveryMethod = SmtpDeliveryMethod.Network 
    client.EnableSsl = True 
    client.Host = "smtp.gmail.com" 
    client.Port = 25 

    Dim credentials As New NetworkCredential("*****@gmail.com", "****") 
    client.Credentials = credentials 

    'Send the msg 
    Return client.SendMailAsync(msg) 

End Function 
End Class 
+0

很奇怪。在大多數情況下,只有當異步代碼調用異步void方法時,纔會得到此異常。但是,我在發佈的代碼中看不到任何地方。無論如何,使用'async void'是一種反模式,因此請檢查您的項目是否有可能正在執行的地方,並使用'async Task'。 –

回答

1

你需要讓你的服務功能異步和等待了。