首页 > 解决方案 > 如何显示自定义错误页面而不是 iis 403 错误页面?

问题描述

我的 web.config :

 <customErrors mode="Off" redirectMode="ResponseRewrite" defaultRedirect="~/Pages/Error/DefaultError.aspx">
      <error statusCode="404" redirect="~/Pages/Error/Page404.aspx" />
      <error statusCode="500" redirect="~/Pages/Error/DefaultError.aspx" />
    </customErrors>

<httpErrors existingResponse="Replace" defaultResponseMode="ExecuteURL" errorMode="Custom"> //also used other options for existingResponse
    <remove statusCode="403"/>
    <error statusCode="403" path="~/Pages/Error/PI403.aspx" responseMode="ExecuteURL"/>
</httpErrors>

这是我在 global.asax.cs 文件中的 Application_error 方法:

Server.ClearError(); //clear the error so we can continue onwards

var errorPage = "~/Pages/Error/DefaultError.aspx";
var httpException = ex as HttpException;
if (httpException != null && httpException.GetHttpCode() == (int)HttpStatusCode.NotFound)
    {
        errorPage = "~/Pages/Error/Page404.aspx";
    }
Response.Redirect(errorPage);

我在项目中有日志文件,但该文件仅使用日志记录。如果我使用 myURL/Logs 浏览器链接,我会得到 IIS 403.14 错误页面。如果我编写 myURL/asdeds,我会得到我的自定义错误页面(在我的项目中不存在类似的内容)。因为403异常不会触发Application_Error。我想为所有异常显示我的自定义错误页面。当我将 myURL/Logs 写入 URL 部分时,我应该会看到我的自定义错误页面。

我还在 Application_BeginRequest 中设置了 TrySkipIisCustomError 属性

HttpContext.Current.Response.TrySkipIisCustomErrors = true;

标签: iisglobal-asaxcustom-errorsapplication-error

解决方案


由于 403.14 - Forbidden 错误是 IIS 错误而不是 asp.net 错误。它使用 StaticFile http 处理程序而不是 asp.net http 处理程序。因此,当您遇到此错误时,不会触发 Application_error。

修改自定义错误页面的唯一方法是使用 IIS 自定义错误页面。

正如 Lex 所说,IIS 自定义错误页面不支持“~”。它将自动匹配您的 Web 应用程序根路径。所以你可以使用下面的配置设置。

<httpErrors existingResponse="Replace" defaultResponseMode="ExecuteURL" errorMode="Custom"> //also used other options for existingResponse
    <remove statusCode="403"/>
    <error statusCode="403" path="/Pages/Error/PI403.aspx" responseMode="ExecuteURL"/>
</httpErrors>

您也可以打开 IIS 管理控制台并使用 UI 窗口来修改设置。

在此处输入图像描述


推荐阅读