如何显示自定义错误页面而不是IIS 403错误页面?

时间:2019-09-20 12:07:20

标签: iis global-asax custom-errors application-error

我的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);

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

并且我还在Application_BeginRequest中设置了TrySkipIisCustomError属性

HttpContext.Current.Response.TrySkipIisCustomErrors = true;

2 个答案:

答案 0 :(得分:0)

由于403.14-禁止的错误是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窗口修改设置。

enter image description here

答案 1 :(得分:0)

首先,您必须转到IIS

  1. 选择配置编辑器,如下所示:

enter image description here

  1. 在打开的页面中,打开部分组合框,然后选择httpErrors

enter image description here

  1. 在打开的页面中,解锁defaultPath

enter image description here

  1. 在IIS上为您的应用程序重复步骤1、2和3

enter image description here

  1. 转到应用程序的错误页面

enter image description here

  1. 选择403错误并进行编辑。在编辑操作页面中,可以选择“响应为302重定向”,然后在“绝对URL”文本框中键入自定义错误页面地址。 enter image description here

不要忘记,此操作在服务器上执行。现在,如果将请求发送到服务器(smp:https:// yoursite.com/scripts),并且如果收到错误302,则将打开所需的页面。