我在类库中有一个带有自定义Cache对象的WebSite.所有项目都运行.NET 3.5.我想将此类转换为使用会话状态而不是缓存,以便在我的应用程序回收时保留状态服务器中的状态.但是,当我从Global.asax文件访问方法时,此代码抛出"HttpContext.Current.Session为null"的异常.我这样叫这个班:
Customer customer = CustomerCache.Instance.GetCustomer(authTicket.UserData);
Run Code Online (Sandbox Code Playgroud)
为什么对象总是为空?
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;
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,我已经尝试将IRequiresSessionState添加到类中,但这并没有什么区别.
干杯Jens
Den*_*ger 17
它并不是真正将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
}
}
Run Code Online (Sandbox Code Playgroud)
它在例如Application_Start中不起作用
| 归档时间: |
|
| 查看次数: |
26618 次 |
| 最近记录: |