【问题标题】:custom error page in asp.netasp.net 中的自定义错误页面
【发布时间】:2012-12-12 09:54:06
【问题描述】:

我在 asp.net 中有 Web 应用程序。 我必须实现自定义错误页面。 表示是否发生任何错误(运行时)。 我必须在 errorpage.aspx 上显示异常和堆栈跟踪 我应该从母版页还是在页面级别处理以及如何处理。

<customErrors mode="On" defaultRedirect="~/Error_Page.aspx"></customErrors>

【问题讨论】:

  • 如果您将自定义错误设置为关闭,它只会在 asp 默认异常页面中向您显示错误和堆栈跟踪。不知道这样对你有用吗?
  • 我必须从用户的角度编写有关 ErrorPage.aspx 错误的详细信息和堆栈跟踪

标签: c# asp.net custom-error-pages


【解决方案1】:

你可以在 global.asax 中处理它:

protected void Application_Error(object sender, EventArgs e)
{
   Exception ex = System.Web.HttpContext.Current.Error;
   //Use here
   System.Web.HttpContext.Current.ClearError();
   //Write custom error page in response
   System.Web.HttpContext.Current.Response.Write(customErrorPageContent);
   System.Web.HttpContext.Current.Response.StatusCode = 500;
}

【讨论】:

    【解决方案2】:

    请不要使用重定向来显示错误消息,因为它会破坏 HTTP。如果发生错误,服务器返回适当的 4xx 或 5xx 响应而不是 301 重定向到 200 OK 响应是有意义的。我不知道微软为什么在 ASP.NET 的自定义错误页面功能中添加了这个选项,但幸运的是你不需要使用它。

    我建议使用 IIS 管理器为您生成 web.config 文件。至于处理错误,打开你的Global.asax.cs文件并为Application_Error添加一个方法,然后从内部调用Server.GetLastError()

    【讨论】:

    • 我必须在 ErrorPage.aspx 上编写有关错误的详细信息和堆栈跟踪
    【解决方案3】:

    在 Global.asax 中

    void Application_Error(object sender, EventArgs e) 
    {    
        Session["error"] = Server.GetLastError().InnerException; 
    }
    void Session_Start(object sender, EventArgs e) 
    {      
        Session["error"] = null;
    }
    

    在 Error_Page Page_Load 事件中

    if (Session["error"] != null)
    {
        // You have the error, do what you want
    }
    

    【讨论】:

    • 这不起作用,因为在触发 Application_Error 事件时 Session 对象不可用。
    【解决方案4】:

    使用Elmah dll 以漂亮的用户界面显示您的错误。您可以使用此 DLL 维护日志。

    【讨论】:

      【解决方案5】:

      您可以使用 Server.GetLastError 访问错误;

      var exception = Server.GetLastError();
        if (exception != null)
          {
             //Display Information here
          }
      

      欲了解更多信息:HttpServerUtility.GetLastError Method

      【讨论】:

      • 是这种有效的方式..意味着我必须在每个页面上放置..我应该只处理母版页上的任何错误..
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-03
      • 2016-11-26
      • 2015-11-14
      • 2011-08-13
      • 1970-01-01
      • 2014-06-27
      • 1970-01-01
      相关资源
      最近更新 更多