在ASP.NET MVC中回调后的RedirectToAction

时间:2019-02-15 16:06:57

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

我想在完成某些任务(发送电子邮件)后重定向到操作,但是我无法弄清楚如何正确地做到这一点。

这是我的代码,但是RedirectToAction在这里什么也没做!

[HttpPost]
public ActionResult SendEmail(EmailContentViewModel emailDetails)
{
    using (MailMessage email = new MailMessage(emailDetails.from, emailDetails.to))
    {
        email.Subject = emailDetails.subject;
        email.Body = emailDetails.body;
        email.Priority = emailDetails.MailPriority;

        processSendingEmail(email, (result) =>
        {
            RedirectToAction("ContactResult", "Contact", new { success = result }); //It's not redirecting to the ContactResult page!
        });
    }

    return null;
}

private void processSendingEmail(MailMessage email, Action<bool> callback= null)
    {
        using (SmtpClient smtpClient = new SmtpClient(_smtpHostName, _smtpPort))
        {
            bool sentSuccessfully = false;

            try
            {
               //.............//
            }
            catch(Exception e)
            {
               //.............//
            }

            callback?.Invoke(sentSuccessfully);
        }
    }

基于Panagiotis Kanavos's response,下面是有效的代码:

    [HttpPost]
    public async Task<ActionResult> SendEmail(EmailContentViewModel emailDetails)
    {
        using (MailMessage email = new MailMessage(emailDetails.from, emailDetails.to))
        {
            email.Subject = emailDetails.subject;
            email.Body = emailDetails.body;
            email.Priority = emailDetails.MailPriority;

            var sentSuccessfully= await processSendingEmail(email);

            return RedirectToAction("ContactResult", "Contact", new { success = sentSuccessfully});
        }
    }


    private async Task<bool> processSendingEmail(MailMessage email)
    {
        var client = new MailKit.Net.Smtp.SmtpClient();
        //Configure the client here ...
        try
        {
            var msg = (MimeKit.MimeMessage)email;
            await client.SendAsync(msg);
            return true;
        }
        catch (Exception ex)
        {
            Debug.Fail(ex.Message);
            string errorMessage = "";
            switch (ex)
            {
                case SmtpFailedRecipientException f:
                    errorMessage = $"Failed to send to {f.FailedRecipient}";
                    break;
                case SmtpException s:
                    errorMessage = "Protocol error";
                    break;
                default:
                    errorMessage = "Unexpected error";
                    break;
            }

            //Do anything you want with the error message

            return false;
        }
    }

3 个答案:

答案 0 :(得分:4)

不要使用回调。 RedirectToAction创建应由操作返回的ActionResult,它不会强制重定向。

异步执行操作的正确方法是使用异步/等待。即使您的电子邮件库没有基于任务的异步方法,您也可以使用TaskCompletionSource将其调整为基于任务的模型。尽管大多数库已从旧的异步模型(如回调,事件和APM)转移到任务,但这将是非常不寻常的。

MailMessage建议您使用SmtpClientSendMailAsync方法是基于任务的,这意味着您可以编写

await client.SendMailAsync(email);

例如:

[HttpPost]
public async Task<ActionResult> SendEmail(EmailContentViewModel emailDetails)
{
    SmptClient client = ... //Configure the client here
    using (MailMessage email = new MailMessage(emailDetails.from, emailDetails.to))
    {
        email.Subject = emailDetails.subject;
        email.Body = emailDetails.body;
        email.Priority = emailDetails.MailPriority;

        await client.SendMailAsync(email);
        return RedirectToAction("ContactResult", "Contact", new { success = true }); 
    };
}

SmptClient是一个过时的类。其文档页面警告:

  

我们不建议您将SmtpClient类用于新开发。有关更多信息,请参见不应使用SmtpClient on GitHub

该链接说明:

  

SmtpClient不支持许多现代协议。它仅兼容。这对于从工具发送一封电子邮件非常有用,但无法适应该协议的现代要求。

建议使用更新的库,例如MailKit

MailKit允许将MailMessage显式转换为MimeMessage,从而可以轻松地将现有代码转换为MailKit:

[HttpPost]
public async Task<ActionResult> SendEmail(EmailContentViewModel emailDetails)
{
    var client = new MailKit.Net.Smtp.SmptClient();
    /Configure the client here ...
    using (MailMessage email = new MailMessage(emailDetails.from, emailDetails.to))
    {
        email.Subject = emailDetails.subject;
        email.Body = emailDetails.body;
        email.Priority = emailDetails.MailPriority;

        var msg=(MailKit)email;
        await client.SendAsync(msg);
        return RedirectToAction("ContactResult", "Contact", new { success = true }); 
    };
}

错误处理

MailKit和旧的SmptClient的Send方法都成功或抛出。一种选择是只隐藏异常并返回true / false成功标志:

try
{
    await client.SendAsync(msg);
    return RedirectToAction("ContactResult", "Contact", new { success = true});
}
catch
{
    return RedirectToAction("ContactResult", "Contact", new { success = false});
}

对于试图诊断可能问题的用户或管理员来说,这不是很有帮助。方法的文档说明了可能发生的异常类型,例如:ArgumentNullException用于空消息,InvalidOperationException,SmtpFailedRecipientException等。

至少,代码可以在返回失败之前记录异常:

catch(Exception ex)
{
    _log.Error(ex);
    return RedirectToAction("ContactResult", "Contact", new { success = false});
}

一个更好的主意是处理特定的异常并可能警告用户:

catch(SmtpFailedRecipientException ex)
{
    _log.Error(ex);
    return RedirectToAction("ContactResult", "Contact", new { success = false,message=$"Couldn't send the message to {ex.FailedRecipient}"});
}
catch(SmtpException ex)
{
    _log.Error(ex);
    return RedirectToAction("ContactResult", "Contact", new { success = false,message="Failed to send the message"});
}
catch(Exception ex)
{
    _log.Error(ex);
    return RedirectToAction("ContactResult", "Contact", new { success = false,message="An unexpected error occured"});
}

C#7中的模式匹配使此操作更容易:

catch(Exception ex)
{
    _log.Error(ex);
    string message="";
    switch (ex)
    {
        case SmtpFailedRecipientException f:
            message=$"Failed to send to {f.FailedRecipient}"; 
            break;
        case SmptException s :
            message="Protocol error";
            break;
        default:
            message="Unexpected error";
            break;
    }
    return RedirectToAction("ContactResult", "Contact", new { success = false,message=message});
}

单独的方法

将发送代码重构为单独的方法很容易。可以将try / catch块和客户端声明提取为单独的方法:

async Task<string> MySendMethod(MailMessage email)
{
    var client = new MailKit.Net.Smtp.SmptClient();
    //Configure the client here ...
    try
    {
        var msg=(MailKit)email;
        await client.SendAsync(msg);
        return "";
    }
    catch(Exception ex)
    {
        _log.Error(ex);
        switch (ex)
        {
            case SmtpFailedRecipientException f:
                return $"Failed to send to {f.FailedRecipient}"; 
            case SmptException s :
                return "Protocol error";
            default:
                return "Unexpected error";
        }
    }
}

该方法将返回结果字符串,而不是返回RedirectToActionResult。如果为空,则操作成功。控制器动作可以这样重写:

[HttpPost]
public async Task<ActionResult> SendEmail(EmailContentViewModel emailDetails)
{
    using (MailMessage email = new MailMessage(emailDetails.from, emailDetails.to))
    {
        email.Subject = emailDetails.subject;
        email.Body = emailDetails.body;
        email.Priority = emailDetails.MailPriority;

        var message=await MySendMethod(email);
        return RedirectToAction("ContactResult", "Contact", 
                   new { success = String.IsNullOrWhitespace(result),
                         message=message 
                   }); 
    };
}

答案 1 :(得分:0)

使用任务基ActionResult进行回调

[HttpPost]
public async Task<ActionResult> SendEmail(EmailContentViewModel emailDetails)
{
   using (MailMessage email = new MailMessage(emailDetails.from, emailDetails.to))
   {
       email.Subject = emailDetails.subject;
       email.Body = emailDetails.body;
       email.Priority = emailDetails.MailPriority;

       var result = await processSendingEmail(email);
       return RedirectToAction("ContactResult", "Contact", new { success = result }); 
   }
}

async Task<bool> processSendingEmail(System.Net.Mail.MailMessage email) {            
    await Task.Delay(1000); //email code here...
    return true;
}

答案 2 :(得分:-2)

尝试这个=>以这种方式调用您的函数

if(processSendingEmail(email, (result)))
{
    return RedirectToAction("ContactResult", "Contact", new { success = result });
}
else
{ 
    return null;
}