AspNet MVC标识 - SendAsync HttpStatusCode

时间:2016-07-14 06:03:46

标签: c# asp.net-mvc asp.net-identity

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

是否可以从此SendAsync电子邮件方法返回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.MembershipReboot https://weblog.west-wind.com/posts/2015/Apr/29/Adding-minimal-OWIN-Identity-Authentication-to-an-Existing-ASPNET-MVC-Application

我不需要基于外部的认证。

也许我需要另一种方法来返回StatusCode并以某种方式连接而不是SendAsync。

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

2 个答案:

答案 0 :(得分:0)

我认为您需要使用其他方法发送请求,例如

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

答案 1 :(得分:0)

我使用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,但这需要进行一些重构(您需要一种记录电子邮件是否已发送的方法,以便您知道是否你需要重试。)