是否存在阻止Response.Redirect在try-catch块内工作的东西?
我在response.redirect()
遇到了一些奇怪的错误,而且项目根本没有构建..当我删除了围绕代码块的try-catch块时, Response.Redirect()
在其中正常工作..
只是想知道这是一个已知的问题还是什么……
如果我没记错的话, Response.Redirect()
抛出一个exception来中止当前请求( ThreadAbortedException
或类似的东西)。 所以你可能会抓住那个例外。
编辑:
此知识库文章描述了此行为(也适用于Request.End()
和Server.Transfer()
方法)。
对于Response.Redirect()
,存在一个重载:
Response.Redirect(String url, bool endResponse)
如果传递endResponse=false
,则不抛出exception(但运行时将继续处理当前请求)。
如果endResponse=true
(或者如果使用了其他重载),则抛出exception并立即终止当前请求。
正如Martin所指出的,Response.Redirect抛出一个ThreadAbortException。 解决方案是重新抛出exception:
try { Response.Redirect(...); } catch(ThreadAbortException) { throw; // EDIT: apparently this is not required :-) } catch(Exception e) { // Catch other exceptions }
Martin是正确的,当您使用Response.Redirect时会抛出ThreadAbortException,请参阅此处的kb文章
您可能引用了在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无法返回(无法返回到它)。
编辑:另一方面,我可能已经把所有这一切都推倒了。 抱歉。