1

我的应用程序使用MVC4Entity Framework 6。我希望自定义操作在发生错误时返回页面错误(500、404、403),使用 MVC 上的过滤器操作。

目前,我正在使用Application_Error文件Global.asax中的方法来返回页面错误,但是当从 AJAX 调用操作时它不起作用。

前任:

这是页面

[ExecuteCustomError]
public ActionResult TestAction()
{
    Rerurn View();
}

这是 AJAX 调用后返回的视图

[ExecuteCustomError]
public ActionResult ReturnView()
{
    //If return error code, i have return message error here.
    return PartialView();
}
4

1 回答 1

1

看起来您没有提供错误页面的正确路径。就像您需要在共享视图文件夹中添加错误页面一样,您可以访问此页面。如果您的页面位于其他文件夹中,那么您必须指定错误视图页面的正确路径。如下所示:

return PartialView("~/Views/ErrorPartialView.cshtml", myModel);

我们还有其他选项可以通过网络调用错误页面。在配置文件中,您可以进行以下设置:

<configuration> ... <system.webServer> ... <httpErrors errorMode="Custom" existingResponse="Replace"> <clear /> <error statusCode="400" responseMode="ExecuteURL" path="/ServerError.aspx"/> <error statusCode="403" responseMode="ExecuteURL" path="/ServerError.aspx" /> <error statusCode="404" responseMode="ExecuteURL" path="/PageNotFound.aspx" /> <error statusCode="500" responseMode="ExecuteURL" path="/ServerError.aspx" /> </httpErrors> ... </system.webServer> ... </configuration>

这里我们使用全局异常过滤器:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCGlobalFilter.Filters
{
    public class ExecuteCustomErrorHandler : ActionFilterAttribute, IExceptionFilter
    {
        public void OnException(ExceptionContext filterContext)
        {
            Exception e = filterContext.Exception;
            filterContext.ExceptionHandled = true;
            filterContext.Result = new ViewResult()
            {
                ViewName = "CommonExceptionPage"
            };
        }
    }
}

现在您必须ExecuteCustomErrorHandler在文件中注册您的课程Global.asax

/// <summary>
/// Application start event
/// </summary>
protected void Application_Start()
{
       AreaRegistration.RegisterAllAreas();
       FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
       RouteConfig.RegisterRoutes(RouteTable.Routes);
       BundleConfig.RegisterBundles(BundleTable.Bundles);
       log4net.Config.XmlConfigurator.Configure();

       // Calling Global action filter
       GlobalFilters.Filters.Add(new ExecuteCustomErrorHandler());
}

您需要CommonExceptionPage在共享文件夹中添加视图:

CommonExceptionPage.cshtml

@{
    ViewBag.Title = "Execute Custom Error Handler";
}

<hgroup class="title">
    <h1 class="error">Error.</h1>
    <h2 class="error">An error occurred while processing your request.</h2>
</hgroup>
于 2017-08-07T03:33:52.407 回答