HttpContext.Current.Session为空。

12

我有一个包含自定义缓存对象的类库的网站,所有项目都在运行.NET 3.5。 我想将这个类转换为使用Session状态而不是缓存,以便在应用程序重启时在状态服务器中保留状态。 然而,当我从Global.asax文件访问方法时,该代码会抛出一个异常,指示"HttpContext.Current.Session为空"。我调用类的方式如下:

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添加到类中,但这并没有任何区别。

Cheers Jens


如果您尝试从Application_Start访问会话,那么此时还没有活动会话。 - onof
2个回答

18

这并不是关于在类中包含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中,它将无法工作。


我在 void Application_AuthenticateRequest(object sender, EventArgs e) 中调用它,所以这样行不通? - M Raymaker
是的,这是不行的。当调用此方法时,会话始终为空,您可以通过简单地进行调试并检查Context.Handler是否为IRequiresSessionStateIReadOnlySessionState来测试它,但这种情况从未发生过。然而,根据我的经验,Application_PreRequestHandlerExecute适用于此,尽管我不确定您的目标是什么。 - Dennis Röttger

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 Mode 的限制。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接