HttpContext.Current.Session - null
У меня есть WebSite с пользовательским объектом Cache внутри библиотеки классов. Все проекты запущены .NET 3.5.
Я хотел бы преобразовать этот класс для использования состояния сеанса вместо кеша, чтобы сохранить состояние в сервере состояний, когда мое приложение перезагружается.
Однако этот код генерирует исключение, когда "HttpContext.Current.Session равно null", когда я посещаю методы из моего файла Global.asax. Я вызываю класс следующим образом:
Customer customer = CustomerCache.Instance.GetCustomer(authTicket.UserData);
Почему объект allways 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 в класс, но это не имеет значения.
Приветствия
Jens
Ответы
Ответ 1
На самом деле речь не идет о включении состояния внутри вашего класса, а скорее о том, где вы называете это в своем 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
}
}
Это не сработает, например. в Application_Start
Ответ 2
В зависимости от того, что вы пытаетесь сделать, вы также можете использовать Session_Start и Session_End в Global.asax:
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.
}
Обратите внимание на ограничения режима SessionState, прежде чем полагаться на Session_End.