ASP.NET自定义错误,除了404错误,

时间:2009-03-20 04:40:55

标签: asp.net

我设置了自定义错误,如下所示..

protected void Application_Error(Object sender, EventArgs e)
{
    Exception ex = HttpContext.Current.Server.GetLastError();
    if (ex is HttpUnhandledException && ex.InnerException != null)
        ex = ex.InnerException;
    if (ex != null)
    {
        try
        {
            Logger.Log(LogEventType.UnhandledException, ex);
        }
        catch
        { }
    }

    HttpContext.Current.Server.ClearError();
    Response.Redirect(MyCustomError);

}

我想知道是否有可能检测到此错误是否为404错误,然后显示默认的404错误?

2 个答案:

答案 0 :(得分:6)

我不得不说我真的很困惑你为什么要清除发生的错误,然后首先重定向到自定义错误页面。

也许改变:

HttpContext.Current.Server.ClearError();
Response.Redirect(MyCustomError);
//to
if (!(ex is HttpException && 404 == ((HttpException)ex).getHttpCode())){
  HttpContext.Current.Server.ClearError();
  Response.Redirect(MyCustomError);
}

否则不要执行任何这些检查并留下任何未找到的文件例外。让它们由web.config中通过框架定义的自定义错误处理程序处理。

<customErrors mode="RemoteOnly" defaultRedirect="~/Error/500.htm">
    <error statusCode="500" redirect="~/Error/500.htm"/>
    <error statusCode="404" redirect="~/Error/404.htm"/>
</customErrors>

如果您没有看到要处理的操作,请将模式更改为“开启”。

如果您需要抛出404,可能是因为已从DB中删除了所请求项目的ID,则抛出相应的HttpException错误。

答案 1 :(得分:1)

我很确定静态文件的请求不会通过Asp.Net框架 - 只有以.aspx结尾的文件才能执行。因此,对不存在的静态文件的请求将从IIS获取404,但不会被asp.net处理。

您可以执行与此页面“IIS Custom 401 Errors”标题下所述类似的操作:

http://msdn.microsoft.com/en-us/library/ms972958.aspx

它的要点是在iis中创建一个自定义错误处理程序,将用户发送到某个静态htm文件,该文件将它们重定向到特殊的404处理程序aspx页面。