c# - HttpContext.Current.Session 为空

标签 c# asp.net

我有一个网站,在类库中有一个自定义缓存对象。所有项目都运行 .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 添加到类中,但这并没有什么不同。

干杯 延斯

最佳答案

这并不是真正将状态包含在您的类中,而是您在 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

关于c# - HttpContext.Current.Session 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5868599/

相关文章:

c# - C#套接字服务器无法多次从同一客户端连接接收数据

asp.net - 向 asp.net 添加样式表(使用 Visual Studio 2010)

.net - ASP.Net 移动 Web 表单发生了什么?

c# - Xpath 抓取链接节点之间的单独文本

c# - "T"在 C# 中是什么意思?

c# - .NET 如何比较两个代表文件名的字符串正确忽略大小写

c# - 如何自定义 Get 属性?

c# - 如何为 IoT 中心的每个新生产者添加新的 Kafka 主题?

c# - 以 DataTable 作为源的 GridView 不自动分页或排序

c# - 具有自定义身份验证的 ASP.NET Web API