从 Global.asax 重定向

Redirect from Global.asax

HttpContext.Current.Response.Redirect("~/default.aspx");

当我在 session_end 在 global.asax 中使用此代码时 我的错误:

Object reference not set to an instance of an object.

为什么?!

当引发事件 SessionEnd 时,Request 和 Response 为空。

HttpContext.Current.Response //this is null

这是设计使然:会话不是在请求期间结束,而是在会话超时时结束

通常(默认配置)在最后一次请求后 20 分钟发生。

因为没有请求所以也没有响应。

You need to understand better how Asp.net Session State works

无论如何,如果您想在会话过期时将用户重定向到某个页面,您可以检查存储在会话中的变量之一:

protected void Page_Load(object sender, EventArgs e)
{
    if (Session["YOUR_VAR_NAME"]==null)
    {
        Response.Redirect("~/default.aspx");
    }
}

Session_end 不是应用程序用户调用的事件,它是会话超时时服务器调用的事件。因此,当您尝试访问 HttpContext 时,它为空,因为没有要访问的 HttpContext(当前没有用户正在与您的站点执行某种交互)。

无论您做什么,尝试重定向不存在的 HttpContext 都会失败。

Session_End 由服务器根据内部计时器在内部触发。因此,当发生这种情况时,没有关联的 HttpRequest。这就是为什么 Response.Redirect 或 Server.Transferdoes 没有意义也不会起作用的原因。

希望以上信息对您有所帮助