是否存在阻止Response.Redirect在try-catch块内工作的东西?

时间:2009-06-30 13:14:58

标签: c# .net visual-studio-2008 try-catch

我在response.redirect()时遇到了一些奇怪的错误,项目根本没有构建..当我删除了围绕代码块{em}的 try-catch 块时1}}它正常运作..

只是想知道这是一个已知的问题还是什么......

5 个答案:

答案 0 :(得分:23)

如果我没记错的话,Response.Redirect()会抛出异常以中止当前请求(ThreadAbortedException或类似的东西)。所以你可能会抓住这个例外。

编辑:

KB article描述了此行为(也适用于Request.End()Server.Transfer()方法)。

对于Response.Redirect(),存在重载:

Response.Redirect(String url, bool endResponse)

如果传递endResponse=false,则不会抛出异常(但运行时将继续处理当前请求)。

如果endResponse=true(或者如果使用了其他重载),则抛出异常并立即终止当前请求。

答案 1 :(得分:4)

正如Martin所指出的,Response.Redirect会抛出一个ThreadAbortException。解决方案是重新抛出异常:

try  
{
   Response.Redirect(...);
}
catch(ThreadAbortException)
{
   throw; // EDIT: apparently this is not required :-)
}
catch(Exception e)
{
  // Catch other exceptions
}

答案 2 :(得分:3)

Martin是正确的,当您使用Response.Redirect时会抛出ThreadAbortException,请参阅kb article here

答案 3 :(得分:0)

您可能引用了在try块中声明的变量。

例如,以下代码无效:

try
{
  var b = bool.Parse("Yeah!");
}
catch (Exception ex)
{
  if (b)
  {
    Response.Redirect("somewhere else");
  }
}

您应该将b声明移出try-catch块之外。

var b = false;
try
{
  b = bool.Parse("Yeah!");
}
catch (Exception ex)
{
  if (b)
  {
    Response.Redirect("somewhere else");
  }
}

答案 4 :(得分:-3)

我认为这里没有任何已知问题。

你根本无法在try / catch块中执行Redirect(),因为Redirect将当前控件留给另一个.aspx(例如),这使得catch无法返回(无法返回) 。

编辑:另一方面,我可能已经将所有这些都计算在后面。遗憾。