gpt4 book ai didi

c# - HttpContext.Current.Session 为空

转载 作者:可可西里 更新时间:2023-11-01 08:21:34 26 4
gpt4 key购买 nike

我有一个网站,在类库中有一个自定义缓存对象。所有项目都运行 .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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com