加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 06:51:26 所属栏目: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 != n
我设置了自定义错误如下..

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错误?

解决方法

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

也许改变:

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错误.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读