【问题标题】:Redirect to error page重定向到错误页面
【发布时间】:2010-12-16 18:52:41
【问题描述】:

我想在发生异常时使用 Response.Redirect 重定向浏览器。
我还想将异常消息传递到我的错误页面。

例如:

string URL = "Page2.aspx?Exception=" + ex.ToString()
Response.Redirect(URL)

可以吗?这是正确的语法吗?

【问题讨论】:

    标签: c# .net asp.net exception response.redirect


    【解决方案1】:

    您应该调用Server.Transfer,而不是Response.Redirect,它会向客户端发送响应,要求它请求不同的页面,它会立即运行不同的页面并将该页面直接发送给客户端。

    然后您可以将异常放入HttpContext.Items 并从错误页面中的HttpContext.Items 中读取。

    例如:

    catch (Exception ex) {
        HttpContext.Current.Items.Add("Exception", ex);
        Server.Transfer("Error.aspx");
    }
    

    Error.aspx 中,你可以得到这样的异常:

    <% 
        Exception error;
        if (!HttpContext.Current.Items.Contains("Exception"))
           Response.Redirect("/");  //There was no error; the user typed Error.aspx into the browser
        error = (Exception)HttpContext.Current.Items["Exception"];
    %>
    

    【讨论】:

      【解决方案2】:

      是的,这会起作用(当然添加了一些分号,您可能只想发送异常消息):

      String URL = "Page2.aspx?Exception=" + ex.Message;
      Response.Redirect(URL);
      

      【讨论】:

        【解决方案3】:

        正如安德鲁所说,它应该可以工作。

        但是,如果您正在寻找错误管理,最好使用Server.GetLastError(),这样您就可以获得包含堆栈跟踪的完整Exception 对象。

        这里一般是MSDN article that deals with Application Errors,使用Server.GetLastError()

        【讨论】:

          【解决方案4】:

          通常我会在我的页面中有面板并在 catch 块中切换可见性以向用户显示友好的消息。我还会向自己发送一封电子邮件报告,详细说明错误消息。

          try
          {
          
          }
          catch (Exception ex)
          {
              formPanel.Visible = false;
              errorPanel.Visible = true;
          
              // Log error
              LogError(ex);
          }
          

          至于报告/转发错误到另一个页面:

          string errorURL = "ErrorPage.aspx?message=" + ex.Message;
          Response.Redirect(errorURL, true);
          

          别忘了 ELMAH! http://bit.ly/HsnFh

          【讨论】:

            【解决方案5】:

            我们始终建议不要在出现错误时重定向到 .aspx 页面。

            在过去,我们已经看到应用程序的基本问题导致发生错误的情况,该错误又重定向到 error.aspx 页面,它自身出错导致无休止的重定向循环。

            我们强烈建议人们使用 .htm 页面或不由 ASP.NET 框架处理的错误页面。

            在 ASP.NET 中使用 Web.config 的 customErrors 部分内置支持自动处理错误重定向。

            customError tag

            您也可以查看全局异常处理,这可以通过您可以在 global.asax 中找到的 Application_OnError 事件进行管理

            谢谢,

            菲尔

            http://exceptioneer.com

            【讨论】:

              猜你喜欢
              • 2023-03-27
              • 1970-01-01
              • 2012-09-11
              • 1970-01-01
              • 1970-01-01
              • 2016-09-02
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多