gpt4 book ai didi

c# - ASP.NET 身份发送电子邮件 : TaskCanceledException

转载 作者:行者123 更新时间:2023-11-30 20:47:56 25 4
gpt4 key购买 nike

我尝试在 asp.net identity 2.0 应用程序中发送验证电子邮件地址电子邮件,但收到 TaskCanceledException 错误。

我尝试了这个线程中的内容:Asp.Net Identity 2.0 - How to Implement IIdentityMessageService to do Async SMTP using SmtpClient?

如果我使用 await 应用程序将永远运行:没有错误消息。但第二个选项返回错误。

错误抛出在:return smtpClient.SendMailAsync(msg);

IdentityConfig.cs

    public async Task SendAsync(IdentityMessage message)
{
// Plug in your email service here to send an email.

try
{
#region formatter
string text = string.Format("Please click on this link to {0}: {1}", message.Subject, message.Body);
string html = "Please confirm your account by clicking this link: <a href=\"" + message.Body + "\">link</a><br/>";

html += HttpUtility.HtmlEncode(@"Or click on the copy the following link on the browser:" + message.Body);
#endregion

MailMessage msg = new MailMessage();
msg.From = new MailAddress("");
msg.To.Add(new MailAddress(message.Destination));
msg.Subject = message.Subject;
msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(text, null, MediaTypeNames.Text.Plain));
msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html));

using (var smtpClient = new SmtpClient())
{
smtpClient.EnableSsl = true;
smtpClient.SendCompleted += (s, e) => { smtpClient.Dispose(); };
await smtpClient.SendMailAsync(msg);
}


}
catch (Exception ex)
{

throw ex;
}


}

注册.aspx.cs

        protected void CreateUser_Click(object sender, EventArgs e)
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var user = new ApplicationUser()
{
UserName = Email.Text,
Email = Email.Text,
UserProfileInfo = new UserProfileInfo
{
FirstName = Firstname.Text,
LastName = Lastname.Text,
Adress = Adress.Text,
Zip = Zip.Text,
City = City.Text,
Mobile = Mobile.Text

}

};
IdentityResult result = manager.Create(user, Password.Text);
if (result.Succeeded)
{
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
string code = manager.GenerateEmailConfirmationToken(user.Id);
string callbackUrl = IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id, Request);
manager.SendEmail(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>.");

manager.AddToRole(user.Id, "Konsument");
IdentityHelper.SignIn(manager, user, isPersistent: false);
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
}
else
{
ErrorMessage.Text = result.Errors.FirstOrDefault();
}
}

最佳答案

@ntl 正确识别了问题:SmtpClient在请求完成之前正在处理实例。但是,我更喜欢使用 asyncawait作为解决方案:

public async Task SendAsync(IdentityMessage message)
{
...
using (var smtpClient = new SmtpClient())
{
smtpClient.EnableSsl = true;
smtpClient.SendCompleted += (s, e) => { smtpClient.Dispose(); };
await smtpClient.SendMailAsync(msg);
}
}

那么,让我们解决原来的问题:

If i use the await the application just runs forever: no error message.

我感觉您的代码可能正在调用 Task.WaitTask<T>.Result在调用 SendAsync 之后.这才是真正的问题:调用代码应该更改为使用 await (这使得调用方法 async 并返回 Task/Task<T> ,这使得 its 调用代码必须使用 await 等)。允许 async通过代码库自然地“成长”。这就是为什么 async 之一我的最佳实践 MSDN article on the subject是“一路异步”。

死锁是因为当你await一个任务,然后 await默认情况下将捕获“当前上下文”(在本例中为 ASP.NET SynchronizationContext ),并使用该上下文恢复 async方法。但是,ASP.NET SynchronizationContext每个请求一次只允许一个线程,因此当调用代码阻塞(通过调用 WaitResult )时,它阻塞了该上下文中的线程和 async方法无法恢复。我更详细地描述了这种死锁情况 on my blog .

最好的解决方案是使用 await ,并使用 async一路走来。

关于c# - ASP.NET 身份发送电子邮件 : TaskCanceledException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25307229/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com