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

rid*_*00z 4 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);

}
Run Code Online (Sandbox Code Playgroud)

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

dla*_*lin 6

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

也许改变:

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

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

<customErrors mode="RemoteOnly" defaultRedirect="~/Error/500.htm">
    <error statusCode="500" redirect="~/Error/500.htm"/>
    <error statusCode="404" redirect="~/Error/404.htm"/>
</customErrors>
Run Code Online (Sandbox Code Playgroud)

如果您没有看到要处理的操作,请将模式更改为"开".

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