[英]Is there something that prevents Response.Redirect to work inside try-catch block?
我在response.redirect()
得到了一些奇怪的错误,而且项目根本没有构建..当我删除了围绕代码块的try-catch块时, Response.Redirect()
在其中正常工作..
只是想知道这是一个已知的问题还是什么......
如果我没记错的话, Response.Redirect()
抛出一个异常来中止当前请求( ThreadAbortedException
或类似的东西)。 所以你可能会抓住那个例外。
编辑:
此知识库文章描述了此行为(也适用于Request.End()
和Server.Transfer()
方法)。
对于Response.Redirect()
,存在一个重载:
Response.Redirect(String url, bool endResponse)
如果传递endResponse=false
,则不会抛出异常(但运行时将继续处理当前请求)。
如果endResponse=true
(或者如果使用了其他重载),则抛出异常并立即终止当前请求。
正如Martin所指出的,Response.Redirect抛出一个ThreadAbortException。 解决方案是重新抛出异常:
try
{
Response.Redirect(...);
}
catch(ThreadAbortException)
{
throw; // EDIT: apparently this is not required :-)
}
catch(Exception e)
{
// Catch other exceptions
}
您可能引用了在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");
}
}
我认为这里没有任何已知问题。
你根本无法在try / catch块中执行Redirect(),因为Redirect将当前控件留给另一个.aspx(例如),这使得catch无法返回(无法返回到它)。
编辑:另一方面,我可能已经把所有这一切都推倒了。 抱歉。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.