2011-05-03 64 views
11

我有一个类库内的自定义Cache对象的WebSite。所有的项目都运行.NET 3.5。 我想将此类转换为使用会话状态而不是缓存,以便在应用程序回收时保持状态服务器中的状态。 但是,当我访问我的Global.asax文件中的方法时,此代码将抛出一个异常,并显示“HttpContext.Current.Session为null”。我这样称呼类:HttpContext.Current.Session为空

Customer customer = CustomerCache.Instance.GetCustomer(authTicket.UserData); 

为什么对象allways null?

public class CustomerCache: System.Web.SessionState.IRequiresSessionState 
{ 
    private static CustomerCache m_instance; 

    private static Cache m_cache = HttpContext.Current.Cache; 

    private CustomerCache() 
    { 
    } 

    public static CustomerCache Instance 
    { 
     get 
     { 
      if (m_instance == null) 
       m_instance = new CustomerCache(); 

      return m_instance; 
     } 
    } 

    public void AddCustomer(string key, Customer customer) 
    { 
     HttpContext.Current.Session[key] = customer; 

     m_cache.Insert(key, customer, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 20, 0), CacheItemPriority.NotRemovable, null); 
    } 

    public Customer GetCustomer(string key) 
    { 
     object test = HttpContext.Current.Session[ key ]; 

     return m_cache[ key ] as Customer; 
    } 
} 

正如你所看到的,我已经尝试将IRequiresSessionState添加到类中,但这并没有什么区别。

干杯 延

+0

如果您尝试从Application_Start访问会话,则还没有实时会话。 – onof 2011-05-03 11:30:32

回答

15

这是不是真的对包括您的类中的国家,而是在那里你把它在你的Global.asax。会话在所有方法中都不可用。

的工作的例子是:

using System.Web.SessionState; 

// ... 

protected void Application_PreRequestHandlerExecute(object sender, EventArgs e) 
    { 
     if (Context.Handler is IRequiresSessionState || Context.Handler is IReadOnlySessionState) 
     { 
      HttpContext context = HttpContext.Current; 
      // Your Methods 
     } 
    } 

它不会工作如在的Application_Start

+0

我在void Application_AuthenticateRequest(object sender,EventArgs e)中调用它,所以这是一个不行? – 2011-05-03 11:48:53

+0

是的,这是不行的,当这个方法被称为会话总是空时,你可以通过简单地调试和检查'Context.Handler'是'IRequiresSessionState'还是'IReadOnlySessionState'来测试它,这从来就不是这样。然而,根据我所做的,'Application_PreRequestHandlerExecute'适用于此,尽管我不确定你的目标。 – 2011-05-03 11:53:48

0

取决于你想要做什么,你也可以从在Global.asax中使用在session_start和Session_End中受益:

http://msdn.microsoft.com/en-us/library/ms178473(v=vs.100).aspx

http://msdn.microsoft.com/en-us/library/ms178581(v=vs.100).aspx

void Session_Start(object sender, EventArgs e) 
{ 
    // Code that runs when a new session is started 

} 

void Session_End(object sender, EventArgs e) 
{ 
    // Code that runs when a session ends. 
    // Note: The Session_End event is raised only when the sessionstate mode 
    // is set to InProc in the Web.config file. If session mode is set to StateServer 
    // or SQLServer, the event is not raised. 

} 

注意的限制在依赖Session_End之前在SessionState模式下。

相关问题