首页 > 解决方案 > 如何在不使用 web.config 的情况下从后面的代码中检测错误以创建自定义错误页面?

问题描述

我正在尝试使用 asp.net 中的代码而不是 web.config 检测错误 404 并显示自定义错误页面。该代码不起作用,它只是提供默认错误页面。这是我的代码:

Exception exception = Server.GetLastError();
HttpException httpException = (HttpException)exception;
Server.ClearError();

if (httpException.ErrorCode == 404)
{
    Response.Redirect("Page_Not_Found.aspx");
}

标签: c#asp.netexception

解决方案


更好的方法是通过web.confng如下方式处理它。

<customErrors mode="On" defaultRedirect="~/UnexpectedError.html">
  <error redirect="~/404Error.html" statusCode="404" />
</customErrors>

推荐阅读