【问题标题】:For some invalid requests, Session object becomes null对于某些无效请求,Session 对象变为 null
【发布时间】:2013-03-08 02:03:54
【问题描述】:

我有一个混合(使用 MVC 和经典 ASP 页面)ASP (C#) 网络应用程序 并且需要为 MVC 和遗留代码实现常见的错误处理; 即,我必须检测无效 URL 并将无效请求重新路由到 主页或登录页面(取决于用户是否登录)。

我在“Application_Error”中添加了错误处理代码(参见下面的代码)。

问题如下:登录用户 ID 保存在 Session 对象中 并且对于一些无效的 URL,会话对象变为空:“会话状态在此上下文中不可用”

例如:

对于以下 URL,存在 Session 对象:

 1. http://myserver:49589/test/home/index
 2. http://myserver:49589/test/home/in
 3. http://myserver:49589/test/ho

但是对于下面的 URL,会话对象为空:

 4. http://myserver:49589/te

所以,问题是当我在请求中拼错文件夹名称时,为什么会话对象变为空,以及如何解决这个问题。

路线图如下:

context.MapRoute(
    "default",
    "test/{controller}/{action}/{id}",
    new { action = "Index", id = UrlParameter.Optional }
);


protected void Application_Error(object sender, EventArgs e)
{
    Exception exception = Server.GetLastError();
    Response.Clear();

    HttpException httpException = exception as HttpException;
    if (httpException != null) // Http Exception
    {
        switch (httpException.GetHttpCode())
        {
            case 400: // Bad Request
            case 404: // Page Not Found
            case 500: // Internal Server Error
                {
                    // Clear the error on server.
                    Server.ClearError();

                    ServerConfiguration scfg = ServerConfiguration.Instance;
                    if (ConnxtGen.App.AppUtility.GetCurrentUserID() != -1)
                    {
                        Response.RedirectToRoute("Unity_default", new { controller = "Home", action = "Index" });
                    }
                    else
                    {
                        Response.Redirect(scfg.PagePath + "/login/login.aspx", false);
                    }
                    break;
                }
            default:
                {
                    break;
                }
        }
    }
    // Avoid IIS7 getting in the middle
    Response.TrySkipIisCustomErrors = true;
}

【问题讨论】:

    标签: c# url session request


    【解决方案1】:

    你应该明白的一点是,Session 变量只有在 HttpApplication.AcquireRequestState 事件发生后才可用。

    在您的问题中,您想在会话中获取一些信息的时刻在 Asp.Net 页面生命周期的过程中为时过早。

    我发现这篇文章肯定会更好地解释会话对象何时可用:

    Asp.net What to do if current session is null?

    这是一篇很棒的文章,更详细地解释了 Asp.Net 页面生命周期的整个内部流程:

    ASP.NET Application and Page Life Cycle

    【讨论】:

      猜你喜欢
      • 2019-10-26
      • 1970-01-01
      • 2016-12-07
      • 2020-09-28
      • 2012-01-15
      • 2017-09-08
      • 2017-10-30
      • 2010-09-21
      • 1970-01-01
      相关资源
      最近更新 更多