.Net MVC 自定义错误页面在 IIS8 中不起作用

本文关键字:IIS8 不起作用 MVC 自定义 错误 Net | 更新日期: 2023-09-27 18:36:14

我有一个 .NET MVC 应用程序,我在使用 IIS 8 的服务器上运行自定义错误页面时遇到问题。 在我的整个应用程序中,我正在适当地捕获和抛出异常,并在错误页面上显示一条消息,该消息是根据他们的违规行为定制的。 在调试中通过VS运行应用程序时,以及当我在IIS (6.1)中的本地主机上配置站点时,这一切都在本地运行良好。

然后,我将其部署到安装了 IIS 8 的服务器上。 最初我得到了令人讨厌的默认 500 错误页面:默认 500 错误页面 http://img202.imageshack.us/img202/1352/b8gr.png

在做了一些研究之后,我发现我可以将以下内容添加到 web.config 中,至少会让我得到我友好的错误页面,尽管没有自定义文本:

<system.webServer>
    <httpErrors errorMode="Detailed" />
</system.webServer>

我正在使用以下过滤器完成自定义错误消息:

public class GlobalExceptionFilter : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        if (filterContext.HttpContext.IsCustomErrorEnabled && !filterContext.ExceptionHandled)
        {
            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.StatusCode = 500;
            string controllerName = (string)filterContext.RouteData.Values["controller"];
            string actionName = (string)filterContext.RouteData.Values["action"];
            HandleErrorInfo info = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
            IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();
            ErrorController newController = factory.CreateController(filterContext.RequestContext, "Error") as ErrorController;
            filterContext.RouteData.Values["controller"] = "Error";
            filterContext.Controller = newController;
            //Display specific error message for custom exception, otherwise generic message
            var model = new ErrorViewModel { Exception = info.Exception };
            if (info.Exception.GetType() == typeof(RchiveException) || info.Exception.GetType().IsSubclassOf(typeof(RchiveException)))
                model.Message = info.Exception.Message;
            else
                model.Message = "An error occurred processing your request.";
            filterContext.Controller.ViewData = new ViewDataDictionary(model);
            string actionToCall = "Index";
            if (filterContext.HttpContext.Request.IsAjaxRequest())
                actionToCall = "IndexAjax";
            filterContext.RouteData.Values["action"] = actionToCall;
            newController.ActionInvoker.InvokeAction(filterContext, actionToCall);
        }
    }
}

有什么想法吗?

.Net MVC 自定义错误页面在 IIS8 中不起作用

我遇到了同样的问题,实际上通过将我的配置更改为:

<system.web>
    <customErrors mode="RemoteOnly">
      <error statusCode="404" redirect="/Error/E404" />
    </customErrors>
</system.web>
请将/错误

/E404 更改为自定义错误路径。然后我还补充说:

  <system.webServer>
    <httpErrors existingResponse="PassThrough" errorMode="Detailed"></httpErrors>
  </system.webServer>

我也通过 Plesk 做了一些更改,但我相信 httpErrors 行最终使它正常工作。