在 ASP.NET Web 表单中按钮的 OnClick 方法中,我调用了 Response.Redirect(),这会导致系统中止线程并显示错误消息:
Exception thrown: 'System.Threading.ThreadAbortException' in mscorlib.dll
这里有几个与此类似的问题,使用我更改的他们的解决方案:
Response.Redirect("~/UI/Home.aspx");
到
Response.Redirect("~/UI/Home.aspx", false);
Context.ApplicationInstance.CompleteRequest();
但是我仍然遇到同样的问题。使用调试器,我运行了代码并成功执行,直到我调用了 Response.Redirect();。
点击功能
protected void btnLogin_Click(object sender, EventArgs e)
{
SiteUser s = null;
try
{
string email = txtEmail.Text;
string pwd = txtPwd.Text;
s = DBConnection.login(email, pwd);
}
catch (Exception ex)
{
Console.Write(ex);
lblLoginError.Text = "Error logging in.";
}
if (s != null)
{
Session["UserSession"] = s;
Response.Redirect("~/UI/Home.aspx", false);
Context.ApplicationInstance.CompleteRequest();
}
else
{
lblLoginError.Text = "User not found. Please check your details and try again.";
}
}
对为什么会发生这种情况有任何想法吗?
最佳答案
我过去曾见过这个问题。理论上,如果你使用这段代码,它不应该发生:
Response.Redirect(url, false);
Context.ApplicationInstance.CompleteRequest();
话虽如此,我有时还是会得到这些,这真是令人惊讶。我猜它有时会出现在事件的 finally
block 中,以指示代码开始清理自己,尽管对你来说似乎并非如此。
我能想到的最好的解决方法是捕获错误并忽略它。
protected void btnLogin_Click(object sender, EventArgs e)
{
try
{
SiteUser s = null;
try
{
string email = txtEmail.Text;
string pwd = txtPwd.Text;
s = DBConnection.login(email, pwd);
}
catch (Exception ex)
{
Console.Write(ex);
lblLoginError.Text = "Error logging in.";
}
if (s != null)
{
Session["UserSession"] = s;
Response.Redirect("~/UI/Home.aspx", false);
Context.ApplicationInstance.CompleteRequest();
}
else
{
lblLoginError.Text = "User not found. Please check your details and try again.";
}
}
catch(System.Threading.ThreadAbortException)
{
//Do nothing. The exception will get rethrown by the framework when this block terminates.
}
}
关于c# - "Exception thrown: ' System.Threading.ThreadAbortException ' in mscorlib.dll"使用 Response.Redirect() 时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42350624/