[英]HttpContext.Current.Session is null
我在 class 库中有一个带有自定义缓存 object 的网站。 所有项目都运行 .NET 3.5。 I would like to convert this class to use Session state instead of cache, in order to preserve state in a stateserver when my application recycles. 但是,当我访问 Global.asax 文件中的方法时,此代码会引发“HttpContext.Current.Session 为空”异常。 我这样称呼 class :
Customer customer = CustomerCache.Instance.GetCustomer(authTicket.UserData);
为什么object总是null?
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 添加到 class 但这并没有什么不同。
干杯詹斯
这并不是要在 class 中包含 State,而是在 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
根据您要执行的操作,您还可以从使用 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 Mode 的限制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.