自定义错误重定向不起作用

Custom error redirect not working

我一直在 asp.net 应用程序中使用自定义错误重定向页面。以下是我的 web.config 代码

 <customErrors mode="On"
  defaultRedirect="DefaultRedirectErrorPage.aspx">
  <error statusCode="404" redirect="Http404ErrorPage.aspx"/>
</customErrors>

DefaultRedirectErrorPage.aspx 存在于根文件夹中,即 MyWebsite/DefaultRedirectErrorPage.aspx 当应用程序根文件夹中的页面发生异常时,它工作正常,例如 MyWebsite/Default.aspx

但是当异常发生在不在根文件夹上的页面例如 MyWebsite/UserControls/MyUserControl.ascx 时,它失败说

找不到页面 MyWebsite\UserControls\DefaultRedirectErrorPage.aspx

我错过了什么?

您为 defaultRedirectredirect 指定的值是您的页面,asp.net 将在导致错误的页面的当前目录中查找。您可以使用 ~/ 从根目录开始,而不考虑导致错误的页面路径。

<customErrors mode="On"
  defaultRedirect="~/DefaultRedirectErrorPage.aspx">
  <error statusCode="404" redirect="~/Http404ErrorPage.aspx"/>
</customErrors>

defaultRedirect

The URL can be absolute (for example, www.contoso.com/ErrorPage.htm) or relative. A relative URL, such as /ErrorPage.htm, is relative to the Web.config file that specified the URL for this attribute, not to the Web page in which the error occurred. A URL starting with a tilde (~), such as ~/ErrorPage.htm, indicates that the specified URL is relative to the root path of the application, MSDN.