AspNet MVC Identity - SendAsync HttpStatusCode

本文关键字:SendAsync HttpStatusCode Identity MVC AspNet | 更新日期: 2023-09-27 17:56:48

将 ASP.NET MVC5与Microsoft.AspNet.Identity v2.2.1一起使用(当前最新版本)

是否可以从此发送异步电子邮件方法返回HttpStatusCode?

它运行良好,发送电子邮件。 问题是当服务失败并出现非 200 HttpStatusCode 时,它会被吞噬。我希望在无法送达电子邮件时通知用户。

public class EmailService : IIdentityMessageService
{
    public async Task SendAsync(IdentityMessage message)
    {
        var client = new RestClient
        {
            BaseUrl = new Uri("https://api.mailgun.net/v3"),
            Authenticator = new HttpBasicAuthenticator("api", GetMailGunKey())
        };
        var request = new RestRequest();
        request.AddParameter("domain", "mg.davestopmusic.com", ParameterType.UrlSegment);
        request.Resource = "{domain}/messages";
        request.AddParameter("from", "Dave Mateer <dave@davestopmusic.com>");
        request.AddParameter("to", message.Destination);
        request.AddParameter("subject", message.Subject);
        request.AddParameter("text", message.Body);
        request.AddParameter("html", message.Body);
        request.Method = Method.POST;
        var response = await client.ExecuteTaskAsync(request);
        int sc = (int) response.StatusCode;
        if (response.StatusCode != HttpStatusCode.OK)
        {
            // display the status code to the user
        }
    }

从此处修改电子邮件确认和密码重置功能:

http://www.asp.net/mvc/overview/security/create-an-aspnet-mvc-5-web-app-with-email-confirmation-and-password-reset

诱惑是转到另一个标识提供者,希望它更具可扩展性:https://github.com/brockallen/BrockAllen.MembershipReboothttps://weblog.west-wind.com/posts/2015/Apr/29/Adding-minimal-OWIN-Identity-Authentication-to-an-Existing-ASPNET-MVC-Application

我不需要基于外部的身份验证。

也许我需要另一种返回状态代码的方法,并以某种方式将其连接起来而不是 SendAsync。

public Task<int> SendAsync2(IdentityMessage message)
{
    // blah
    int sc = (int) response.StatusCode;
    return Task.FromResult(sc);
}

AspNet MVC Identity - SendAsync HttpStatusCode

我使用的是 Postal,所以我的过程有点不同,但我所做的是抛出一个异常,并使用一些异常处理在重新显示表单时显示消息。这是它的简化版本:

1) 如果状态代码不是预期的,则引发异常:

if (response.StatusCode != HttpStatusCode.OK)
{
    // Create this exception at some point.
    // It doesn't need to do anything except inherit Exception
    throw new MyCustomEmailException();
}

2) 在调用您的电子邮件服务的操作中捕获异常:

[HttpPost]
public async Task<ActionResult> ResetPassword(Models.PasswordResetForm model)
{
    try
    {
        // Call your email sending code...
    }
    catch(MyCustomEmailException ex)
    {
        // Remember to log the exception
        ModelState.AddModelError(string.Empty, "We're sorry, we could not complete this request. Please wait a moment and then try again");
    }
    return View(model);
}

您也可以考虑将电子邮件发送到单独的进程,例如 Hangfire,尽管这需要一些重构(您需要一种方法来记录电子邮件是否已发送,以便您知道是否需要重试)。

我认为您需要使用其他方法来发送请求,如下所示

client.ExecuteAsync(request, response => 
{
    int sc = (int)response.StatusCode;
    if (response.StatusCode != HttpStatusCode.OK)
    {
        // display the status code to the user
    }
});