在 MVC 中回调后重定向到操作 ASP.NET



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

这是我的代码,但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的回应,这里有一个工作代码:

[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;
}
}

不要使用回调。重定向到操作创建一个应由操作返回的操作结果,它不会强制重定向。

异步执行某些操作的正确方法是使用 async/await。即使您的电子邮件库没有基于任务的异步方法,您也可以使用 TaskCompletionSource 将其调整为基于任务的模型。不过,这是相当不寻常的,因为大多数库已经从旧的异步模型(如回调、事件和 APM)转移到任务。

MailMessage建议你正在使用SmtpClient。SendMailAsync 方法是基于任务的,这意味着您可以编写

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 类用于新开发。有关详细信息,请参阅不应在 GitHub 上使用 SmtpClient。

该链接解释说:

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方法要么成功,要么抛出。一种选择是隐藏异常并返回真/假成功标志:

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

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

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

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 
}); 
};
}

使用任务库 操作结果 在回调中

[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;
}

相关内容

  • 没有找到相关文章

最新更新