我有一个简单的 Session_Start
看起来像这样的代码:
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
Dim sid = Session.SessionID
Response.Redirect("~/Blog.aspx")
dim dummy=4/0
End Sub
它没有按预期工作。通常在我的整个站点中,每当
Response.Redirect()
被调用,它也终止代码执行。而在这里,即使页面最终重定向,dim dummy=4/0
行也被执行。这导致我在从
Session_Start()
调用的其他代码中出现问题我的假设是重定向是一个导出点。我也试过设置
endResponse
在 Response.Redirect(url, endResponse)
重载方法为 true
或 false
但这也不起作用。
最佳答案
深入研究框架源代码后,我可以解释为什么 Response.Redirect(url, true)
在Session_Start()
中被调用后继续执行代码但不是在后面的常规代码中。Response.Redirect()
最终调用Redirect()
的内部重载方法:
internal void Redirect(string url, bool endResponse, bool permanent)
{
// Miscellaneous goings on
if (endResponse)
{
this.End();
}
}
在此方法结束时,如果
endResponse
那么为真 Response.End()
叫做。当我们看Response.End()
我们看到以下代码:public void End()
{
if (this._context.IsInCancellablePeriod)
{
InternalSecurityPermissions.ControlThread.Assert();
Thread.CurrentThread.Abort(new HttpApplication.CancelModuleException(false));
}
else if (!this._flushing)
{
this.Flush();
this._ended = true;
if (this._context.ApplicationInstance != null)
{
this._context.ApplicationInstance.CompleteRequest();
}
}
}
该方法检查当前上下文的状态
IsInCancellablePeriod
值(value)。这个值是内部的,但我们可以在调试器中看到它:如果我们在
Session_Start()
里面设置一个断点并检查当前上下文的 IsInCancellablePeriod
我们看到的不可见成员:这意味着请求的线程不会被中止,因此
Response.Redirect()
之后的代码无论您是否设置 endResponse
都会执行或不。如果我们在 ASPX 页面的
Page_Load()
中设置断点事件我们看到了不同的东西:当前上下文的
IsInCancellablePeriod
不可见成员设置为 true 等 Thread.CurrentThread.Abort()
将被调用并且在 Response.Redirect()
之后不再执行任何代码.这种行为差异的原因是我怀疑与保护您的 session 状态完整性有关:
Don't redirect after setting a Session variable (or do it right)
如果您需要阻止代码在
Response.Redirect()
之后执行在 Session_Start()
那么你需要使用 If...Then...Else
:If <some_condition_we_have_to_redirect_for> Then
Response.Redirect("~/Blog.aspx")
Else
// Normal session start code goes here
End If
关于asp.net - Session_Start 中的 Response.Redirect 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6029826/