我有一个网站,在类库内有一个自定义缓存对象。所有项目都运行 .NET 3.5。
我想将此类转换为使用会话状态而不是缓存,以便在应用程序回收时保留状态服务器中的状态。
但是,当我访问 Global.asax 文件中的方法时,此代码会引发异常“HttpContext.Current.Session is 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 添加到类中,但这没有什么区别。
干杯
延斯
它并不是真正将 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
}
}
它不会工作,例如在应用程序_启动中
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)