有什么阻止的Response.Redirect到try-catch块内工作?
-
21-08-2019 - |
题
我买了一些response.redirect()
奇怪的错误,该项目并没有在所有的建筑。当我删除的的try-catch 的块被周围的代码块,其中Response.Redirect()
是它工作正常..
只是想知道这是否是一个已知的问题或东西...
解决方案
如果正确地记得Response.Redirect()
抛出异常中止当前请求(ThreadAbortedException
或类似的东西)。所以,你可能会被没收例外。
编辑:
此 KB文章描述了这种行为(也为Request.End()
和Server.Transfer()
方法)。
有关Response.Redirect()
存在一个过载:
Response.Redirect(String url, bool endResponse)
如果你传递endResponse=false
,那么不引发异常(但运行时将继续处理当前的请求)。
如果endResponse=true
(或者如果其它过载时),则抛出异常,并且当前请求将立即被终止。
其他提示
正如马丁指出的,Response.Redirect的抛出一个ThreadAbortException。该解决方案是重新抛出异常:
try
{
Response.Redirect(...);
}
catch(ThreadAbortException)
{
throw; // EDIT: apparently this is not required :-)
}
catch(Exception e)
{
// Catch other exceptions
}
马丁是正确的,一个ThreadAbortException被抛出当您使用的Response.Redirect,请参阅 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块,因为重定向离开电流控制到另一个的.aspx(例如),剩下的捕捉空气中的(不能回来的话) 。
编辑:另外,我可能有这一切想通倒退。遗憾。
不隶属于 StackOverflow