[英]Is there something that prevents Response.Redirect to work inside try-catch block?
I got some weird error with response.redirect()
and the project wasn't building at all.. when I removed the try-catch block that was surrounding the block of code where Response.Redirect()
was in it worked normally.. 我在
response.redirect()
得到了一些奇怪的错误,而且项目根本没有构建..当我删除了围绕代码块的try-catch块时, Response.Redirect()
在其中正常工作..
Just want to know if this is a known issue or something... 只是想知道这是一个已知的问题还是什么......
If I remember correctly, Response.Redirect()
throws an exception to abort the current request ( ThreadAbortedException
or something like that). 如果我没记错的话,
Response.Redirect()
抛出一个异常来中止当前请求( ThreadAbortedException
或类似的东西)。 So you might be catching that exception. 所以你可能会抓住那个例外。
Edit: 编辑:
This KB article describes this behavior (also for the Request.End()
and Server.Transfer()
methods). 此知识库文章描述了此行为(也适用于
Request.End()
和Server.Transfer()
方法)。
For Response.Redirect()
there exists an overload: 对于
Response.Redirect()
,存在一个重载:
Response.Redirect(String url, bool endResponse)
If you pass endResponse=false
, then the exception is not thrown (but the runtime will continue processing the current request). 如果传递
endResponse=false
,则不会抛出异常(但运行时将继续处理当前请求)。
If endResponse=true
(or if the other overload is used), the exception is thrown and the current request will immediately be terminated. 如果
endResponse=true
(或者如果使用了其他重载),则抛出异常并立即终止当前请求。
As Martin points out, Response.Redirect throws a ThreadAbortException. 正如Martin所指出的,Response.Redirect抛出一个ThreadAbortException。 The solution is to re-throw the exception:
解决方案是重新抛出异常:
try
{
Response.Redirect(...);
}
catch(ThreadAbortException)
{
throw; // EDIT: apparently this is not required :-)
}
catch(Exception e)
{
// Catch other exceptions
}
You may have referenced a variable that is declared inside the try block. 您可能引用了在try块中声明的变量。
For example, the below code is invalid: 例如,以下代码无效:
try
{
var b = bool.Parse("Yeah!");
}
catch (Exception ex)
{
if (b)
{
Response.Redirect("somewhere else");
}
}
You should move out the b declaration to outside the try-catch block. 您应该将b声明移出try-catch块之外。
var b = false;
try
{
b = bool.Parse("Yeah!");
}
catch (Exception ex)
{
if (b)
{
Response.Redirect("somewhere else");
}
}
I don't think there is any known issue here. 我认为这里没有任何已知问题。
You simply can't do a Redirect() inside a try/catch block because Redirect leaves the current control to another .aspx (for instance), which leaves the catch in the air (can't come back to it). 你根本无法在try / catch块中执行Redirect(),因为Redirect将当前控件留给另一个.aspx(例如),这使得catch无法返回(无法返回到它)。
EDIT: On the other hand, I might have had all of this figured backwards. 编辑:另一方面,我可能已经把所有这一切都推倒了。 Sorry.
抱歉。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.