无法在Asp.net中保存会话

时间:2014-07-28 17:22:28

标签: asp.net session

我创建了一个基类Page类并尝试将对象保存在会话变量中,但它给出了Object reference not set to an instance of an object.错误。我的对象已初始化并具有值。

我在Web.config文件中添加了enableSessionState="true"sessionState mode="InProc"设置。 ASP.NET State Service也在运行

using System;
using System.Web;
using System.Globalization;
using System.Threading;
using System.Xml.Linq;

public class BasePage : System.Web.UI.Page
{
    public BasePage()
    {
        string catalog = "" + HttpContext.Current.Request.QueryString["c"];
        if (catalog != "")
        {
            Engine eng = new Engine();
            TEngine engine = eng.GetEngines(catalog.ToUpper());
            if (engine != null)
            {
                HttpContext.Current.Session["CurrentEngine"] = engine;
            }
        }
    }
}

的web.config:

<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0"/>
    <sessionState mode="InProc" timeout="60" cookieless="false" />

    <pages enableSessionState="true">
      <controls>
              <add src="~/Components/menu.ascx" tagName="Menu" tagPrefix="uc" />
              <add src="~/Components/footer.ascx" tagName="Footer" tagPrefix="uc" />
              <add src="~/Component/tree.ascx" tagName="Tree" tagPrefix="uc" />

          </controls>        
        </pages>

        <httpModules>
          <add type="System.Web.SessionState.SessionStateModule" name="Session"/>
        </httpModules>

  </system.web>
</configuration>

2 个答案:

答案 0 :(得分:2)

根据this MSDN document,在构建Page对象后,将分配Page的属性(ContextRequest等)。您可以将使用这些属性的代码移动到InitLoad事件处理程序。

并且无需在网页中使用HttpContext.Current。只需使用this.Context

答案 1 :(得分:0)

添加此作为答案,因为它似乎解决了您的问题:

在ASP.NET生命周期中,页面对象的构造发生得太早,而HttpContext.Current尚不可用。将此代码移动到其中一个初始化方法或其中一个,而不是构造函数。

相关问题