问题 HttpContext.Current.Session为null


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

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

干杯 延


9862
2018-05-03 11:14


起源

如果您尝试从Application_Start访问会话,则还没有实时会话。 - onof


答案:


它并不是真正将State包含在你的类中,而是你在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中


15
2018-05-03 11:43



我在void Application_AuthenticateRequest(对象发送者,EventArgs e)中调用它,所以这是不行的? - M Raymaker
是的,这是一个不行,当调用此方法时,Session始终为null,您可以通过简单的调试和检查来测试它 Context.Handler 或者是 IRequiresSessionState 要么 IReadOnlySessionState,情况永远不会如此。但是,基于我所做的, Application_PreRequestHandlerExecute 虽然我不确定你的目标,但仍然可以做到这一点。 - Dennis Röttger


根据您要执行的操作,您还可以从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模式的限制。


0
2018-06-28 13:01