MVC 处理程序错误属性不会重定向到异常时的错误视图

本文关键字:错误 异常 重定向 视图 处理 程序 属性 MVC | 更新日期: 2023-09-27 17:56:18

问题背景:

我的页面上有一个简单的"联系表格"。用户需要提供其姓名、通过电子邮件发送邮件主题和实际邮件本身。

我目前正在尝试实现"错误"视图,将在邮件过程中出现任何错误时显示,例如 uer 提供的电子邮件格式不正确。

问题:

我正在我的主控制器上使用 MVC HandleError 属性,当前在抛出错误时未显示该页面。

法典:这是使用 AJAX 将请求提交到主控制器上的操作方法的联系表单:

@using (Ajax.BeginForm("SendFMFCMail", "Home", new AjaxOptions { UpdateTargetId = "result", OnBegin = "LoadingSpinner", OnSuccess = "MessageSent", OnFailure = "FailedMail" }))
        {
            @Html.ValidationSummary(true)
            <div id="result"></div>
            <div class="row">
                <div class="col-lg-12">
                    <div class="form-group">
                        <div class="row">
                            <div class="col-md-6 form-group">
                                @Html.TextBoxFor(m => m.Name, new { @class = " form-control spanWidth", placeHolder = "Name", id = "name" })
                                @Html.ValidationMessageFor(model => model.Name)
                                @*<input class="form-control spanWidth" id="name" placeholder="Name">*@
                            </div>
                            <div class="col-md-6 form-group">
                                @Html.TextBoxFor(m => m.Email, new { @class = "form-control spanWidth", placeHolder = "Email", id = "email" })
                                @Html.ValidationMessageFor(model => model.Email)
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-sm-12 form-group">
                                @Html.TextBoxFor(m => m.Subject, new { @class = "form-control spanWidth", placeHolder = "Subject", id = "subject" })
                                @Html.ValidationMessageFor(model => model.Subject)
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-sm-12 form-group">
                                @Html.TextAreaFor(m => m.Message, new { @class = "form-control spanHeight spanWidth", placeHolder = "Message", rows = 15, id = "message" })
                                @Html.ValidationMessageFor(model => model.Message)
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-sm-12 form-group">
                                <input type="submit" class="btn btn-primary btn-block spanWidth" value="Send Message" />
                            </div>
                        </div>
                    </div>
                </div>
            </div>

Error.cshtml视图位于项目Shared文件夹中。

我已经确保Web.config CustomErrors On

 <customErrors mode="On" />

这是FilterConfig.cs

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }

HomeController中,我尝试在类的顶部设置一个通用的异常处理程序:

[HandleError(View = "FMFCError")]
public class HomeController : Controller
{
   //code.
}

我也尝试在我的Action方法上设置它,这也不起作用:

注意:我已将显式异常类型设置为SmtpException因为当使用无效电子邮件地址发送电子邮件时,我预计会失败;

[HandleError(ExceptionType = typeof(SmtpException), View = "FMFCError")]
public ActionResult SendFMFCMail(Contact contactDetails)
{
  var emailHandler = new EmailHandler();
    try
    {
        emailHandler.SendMail(contactDetails);
    }
    catch(SmtpException ex)
    {
        throw ex;
    }
    return Json(new { messageStatus = "success" });
}

这是SendMail方法:

public void SendMail(Contact emailMessage)
{
    string sellerEmail = WebConfigurationManager.AppSettings["SellerEmail"];
    MailAddress from = new MailAddress(emailMessage.Email, emailMessage.Name);
    MailAddress to = new MailAddress(sellerEmail);
    MailMessage mail = new MailMessage(from, to);
    mail.Subject = emailMessage.Subject;
    mail.Body = emailMessage.Message;
    SmtpClient client = new SmtpClient()
    {
        Host = "smtp.gmail.com",
        Port = 587,
        EnableSsl = true,
        DeliveryMethod = SmtpDeliveryMethod.Network,
        UseDefaultCredentials = false,
        Credentials = new NetworkCredential(from.Address, WebConfigurationManager.AppSettings["SellerEmailPassword"])
    };
    client.Send(mail);
}

谁能看出我哪里出了问题?

MVC 处理程序错误属性不会重定向到异常时的错误视图

您不能通过 AJAX 帖子重定向。您可以将 URL 发送回要将浏览器重定向到的前端,然后使用 JS 导航到该前端。

后端 - 主控制器

[HttpPost]
public ActionResult GoToMethodName()
{ 
     return Json(Url.Action("Index", "MethodName"));   
}

视图 JS - 这是简单的代码,假设您将在异常或成功时重定向,可以根据您希望如何处理成功来编写更复杂的逻辑处理,这将根据异常捕获的需求修复您的重定向。

    $.ajax({
        type: "POST",
        url: "http://localhost/GoToMethodName",
        dataType: 'json',
        crossDomain: true,
        success: function(data){
            window.location.href = data;
        }
    });