iis - 如何显示自定义错误页面而不是 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;
解决方案
由于 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 窗口来修改设置。
推荐阅读
- javascript - 如何限制 ip 每小时只能提交一次表单
- python-3.x - 如何使用用户输入更新 TextControl 值
- json - Flutter FormatException:意外字符(在字符 1 处)
- python - 如何在 for 和 if 循环中格式化 Python 列表?
- python - 如何将我的 emailpass[0] 和 emailpass[1] 放在 request.get url 上?
- java - 如何生成随机实数列表
- html - 使用 svg dashoffset/dasharray 按 360 度的百分比绘制一个圆
- jquery - 根据纯文本数字打开/关闭复选框
- python - Python在嵌套字典中搜索键/值
- r - 如何使用 R 中的列表条目有效地设置矩阵的值?