首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

Response.Redirect()导致try.catch不执行有关问题

2012-01-05 
Response.Redirect()导致try..catch不执行问题今天进行异常处理时,出现一个奇怪问题,上来向大家讨教下A.as

Response.Redirect()导致try..catch不执行问题
今天进行异常处理时,出现一个奇怪问题,上来向大家讨教下

A.aspx页面
<body>
  <form id="form1" runat="server">
  <div>
  这是A页面,不出现导异常时应该显示这个!!!!
  </div>
  </form>
</body>

B.aspx页面
<body>
  <form id="form1" runat="server">
  <div>
  这是B页面,出异常时应该显示这个!!!!
  </div>
  </form>
</body>

default.aspx页面
<body>
  <form id="form1" runat="server">
  <div>
  <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
  </div>
  </form>
</body>

default.cs文件代码
  protected void Button1_Click(object sender, EventArgs e)
  {
  try
  {
  Response.Redirect("A.aspx");
  }
  catch( Exception e1)
  {
  Response.Redirect("B.aspx");
  //Response.Write("<script>alert('aaaaaaaaaaaa')</script");
  }
  }

运行时 Response.Redirect("B.aspx")这句代码在执行,只看到B.aspx页面,
问下大家为什么会这样!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!



[解决办法]
一般这样写

C# code
        bool hasException = false;        try         {             hasException = false;            //Response.Redirect("A.aspx");         }         catch( Exception e1)         {              hasException = true;            //Response.Redirect("B.aspx");             //Response.Write(" <script>alert('aaaaaaaaaaaa') </script");         }         finally        {            if(hasException )            {               Response.Redirect("B.aspx");             }            else            {               Response.Redirect("A.aspx");             }        }
[解决办法]
MSDN已经解析清楚了

“调用 Redirect 等效于在将第二个参数设置为 true 的情况下调用 Redirect。
Redirect 调用 End,它在完成时引发 ThreadAbortException 异常。”


可见Redirect方法在内部是调用 Thread.Abort()来中止线程的从而引发ThreadAbortException 异常。
如果不想立刻中止则,第二个参数设置为false

C# code
protected void Button1_Click(object sender, EventArgs e)     {         try         {             Response.Redirect("A.aspx",false);         }         catch( Exception e1)         {             Response.Redirect("B.aspx");             //Response.Write(" <script>alert('aaaaaaaaaaaa') </script");         }     } 

热点排行