簡體   English   中英

UserManager.SendEmailAsync掛起

[英]UserManager.SendEmailAsync hangs

我有一個自定義用戶管理器與自定義EmailService。 我在AccountController中調用UserManager.SendEmailAsync()方法,它只是掛起。 我甚至嘗試使用無效的SMTP主機名,然后發生異常,在調試中我可以看到它進入catch塊,但無論返回View(模型)語句,它只是在瀏覽器中“掛起”並繼續加載永遠。

有任何想法嗎?

ApplicationUserManager構造函數:

public ApplicationUserManager(IUserStore<ApplicationUser> store)
    : base(store)
{
    EmailService = new EmailService();
}

EmailService:

public class EmailService : IIdentityMessageService
{
    public async Task SendAsync(IdentityMessage message)
    {
        // Credentials:
        string smtpServer = ConfigurationManager.AppSettings["EmailSmtpServer"];
        int smtpPort = int.Parse(ConfigurationManager.AppSettings["EmailSmtpPort"]);
        bool enableSsl = bool.Parse(ConfigurationManager.AppSettings["EmailEnableSSL"]);
        string smtpUsername = ConfigurationManager.AppSettings["EmailSmtpUsername"];
        string smtpPassword = ConfigurationManager.AppSettings["EmailSmtpPassword"];
        string sentFrom = ConfigurationManager.AppSettings["EmailSentFrom"];

        // Configure the client:
        var client = new SmtpClient(smtpServer, Convert.ToInt32(587));

        client.Port = smtpPort;
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.UseDefaultCredentials = false;
        client.EnableSsl = enableSsl;

        // Create the credentials:
        var credentials = new NetworkCredential(smtpUsername, smtpPassword);
        client.Credentials = credentials;

        // Create the message:
        var mail = new System.Net.Mail.MailMessage(sentFrom, message.Destination);

        mail.Subject = message.Subject;
        mail.Body = message.Body;

        // Send:
        await client.SendMailAsync(mail);
    }
}

AccountController中的ForgotPassword方法

    //
    // POST: /Account/ForgotPassword
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = await UserManager.FindByNameAsync(model.Email);
            // Don't check confirmation status for now
            //if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
            if (user == null)
            {
                ModelState.AddModelError("", "The user either does not exist or is not confirmed.");
                return View();
            }

            // 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.GeneratePasswordResetTokenAsync(user.Id);
            var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
            try
            {
                await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                return View(model);
            }
            return RedirectToAction("ForgotPasswordConfirmation", "Account");
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

這對我有用

ApplicationUserManager構造函數:

public AppUserManager(IUserStore<AppUser> store)
        : base(store)
{
        this.UserTokenProvider = new TotpSecurityStampBasedTokenProvider<AppUser, string>();
        this.EmailService = new EmailService();
}

EmailService:

public class EmailService : IIdentityMessageService
{
    public Task SendAsync(IdentityMessage message)
    {
        // Credentials:
        var credentialUserName = ConfigurationManager.AppSettings["emailFrom"];
        var sentFrom = ConfigurationManager.AppSettings["emailFrom"];
        var pwd = ConfigurationManager.AppSettings["emailPassword"];

        // Configure the client:
        System.Net.Mail.SmtpClient client =
            new System.Net.Mail.SmtpClient("smtp-mail.outlook.com");

        client.Port = 587;
        client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
        client.UseDefaultCredentials = false;

        // Create the credentials:
        System.Net.NetworkCredential credentials =
            new System.Net.NetworkCredential(credentialUserName, pwd);

        client.EnableSsl = true;
        client.Credentials = credentials;

        // Create the message:
        var mail =
            new System.Net.Mail.MailMessage(sentFrom, message.Destination);

        mail.Subject = message.Subject;
        mail.Body = message.Body;

        // Send:
        return client.SendMailAsync(mail);
    }
}

重要信息如果您使用外部郵件提供商,則應修改外部應用程序配置,例如:gmail: 允許安全性較低的應用訪問您的帳戶

AccountController中的ForgotPassword方法

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> RecoveryPassword(LoginInfoModel model)
    {
        if (ModelState.IsValid)
        {
            var user = await UserManager.FindByNameAsync(model.Email);
            if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
            {
                // Don't reveal that the user does not exist or is not confirmed
                return View("ForgotPasswordConfirmation");
            }

            var code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
            var callbackUrl = Url.Action("ResetPassword", "Account",
            new { UserId = user.Id, code = code }, protocol: Request.Url.Scheme);
            await UserManager.SendEmailAsync(user.Id, "Reset Password",
            "Reinicia tu contraseña clicando : <a href=\"" + callbackUrl + "\">aqui</a>");
            return View("ForgotPasswordConfirmation");
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

最后我在郵箱上看到了我的電子郵件

郵箱

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM