HttpContext.Current.Session is null

本文关键字:null is Session Current HttpContext | 更新日期: 2023-09-27 17:54:38

我有一个网站与自定义缓存对象内的类库。所有的项目都在运行。net 3.5。我想将该类转换为使用会话状态而不是缓存,以便在应用程序回收时在状态服务器中保留状态。然而,这段代码抛出了一个异常"HttpContext.Current"。Session是null",当我访问全局中的方法时。asax文件。我这样调用这个类:

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

为什么对象总是空的?

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添加到类中,但这并没有什么不同。

干杯Jens

HttpContext.Current.Session is null

这并不是关于在类中包含State,而是关于在Global.asax中调用它的位置。Session不是在所有方法中都可用。

一个有效的例子是:

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

根据您想要做的事情,您也可能受益于在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模式的限制