asp.net中服务器传输中的ThreadAbortException
本文关键字:ThreadAbortException 传输 服务器 net asp | 更新日期: 2023-09-27 18:27:53
我在执行行时收到错误Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.
Server.Transfer("Payment.aspx?vpc_ChannelId=2", true);
正如这个答案所指出的https://stackoverflow.com/a/1252119/1169180&https://stackoverflow.com/a/11130517/1169180
我把代码改成
protected void Page_Load(object sender, EventArgs e)
{
try
{
UserContext conObj = new UserContext();
HttpContext CurrContext = HttpContext.Current;
if (!IsPostBack)
{
// Code
}
else
{
string userContext = hdnContextObj.Value;
conObj = JsonConvert.DeserializeObject<UserContext>(userContext);
CurrContext.Items.Add("Context", conObj);
try
{
Server.Transfer("Payment.aspx?vpc_ChannelId=2", true);
}
catch (ThreadAbortException xObj)
{
}
finally
{
Server.Transfer("Payment.aspx?vpc_ChannelId=2", true);
}
}
}
catch (Exception xObj)
{
Response.Write("Exception : " + xObj.Message);
}
}
我仍然在捕获块中得到相同的异常
正如这里所指出的http://support.microsoft.com/kb/312629/EN-US/我使用了Server.Execute
,但它没有重定向到Payment.aspx
页面,而是刷新。
由于传输,运行操作的线程被迫在多个位置终止,因此引发异常。因此,正如您链接的答案所示,忽略此异常是安全的。
您可以通过捕获异常而不抛出异常来忽略该异常。
try
{
Server.Transfer("Payment.aspx?vpc_ChannelId=2", true);
}
catch(ThreadAbortException)
{
// Exception ignored: Thread Abort = discontinue processing on the current page
}
或者,正如MSDN文章所建议的,您可以使用Server.Execute
。
要解决此问题,请使用以下方法之一:
对于
Response.End
,请调用HttpContext.Current.ApplicationInstance.CompleteRequest
方法而不是Response.End
,以绕过对Application_EndRequest
事件的代码执行。对于
Response.Redirect
,使用重载Response.Redirect(String url, bool endResponse)
,该重载传递false
作为endResponse
参数,以抑制对Response.End
的内部调用。例如:Response.Redirect ("nextpage.aspx", false);
如果使用此解决方法,将执行Response.RRedirect后面的代码。
对于
Server.Transfer
,请改用Server.Execute
方法
//Server.Execute
澄清
MSDN文档阐明了Server.Execute
的用法。重要的是要记住,这不是重定向,它的作用就像一个函数调用。因此,调用之后的任何代码也将被执行。如果不希望执行代码,可以使用return
或Response.End
。
在OP的例子中,当使用Server.Execute
时,他的代码可能看起来像这样
protected void Page_Load(object sender, EventArgs e)
{
try
{
UserContext conObj = new UserContext();
HttpContext CurrContext = HttpContext.Current;
if (!IsPostBack)
{
// Code
}
else
{
string userContext = hdnContextObj.Value;
conObj = JsonConvert.DeserializeObject<UserContext>(userContext);
CurrContext.Items.Add("Context", conObj);
Server.Execute("Payment.aspx?vpc_ChannelId=2", true);
Response.End(); // or return;
}
}
catch (Exception xObj)
{
Response.Write("Exception : " + xObj.Message);
}
}
Server.Transfer("Payment.aspx?vpc_ChannelId=2",false);
这对你有用。它在传输代码之后停止剩余的代码,这样它就不会执行该代码。
ThreadAbortException异常,原因是在Server.RRedirect和Server.Transfer中内部调用了Response.End。试试这个
Response.Write("<script language='"javascript'" type='"text/javascript'">window.location.href = 'Your.aspx'; </script>");