Asp.net
在 Application_BeginRequest 中設置會話變數
我正在使用 ASP.NET MVC,我需要在
Application_BeginRequest. 問題是此時對象HttpContext.Current.Session始終是null.protected void Application_BeginRequest(Object sender, EventArgs e) { if (HttpContext.Current.Session != null) { //this code is never executed, current session is always null HttpContext.Current.Session.Add("__MySessionVariable", new object()); } }
在 Global.asax 中嘗試 AcquireRequestState。會話在此事件中可用,每個請求都會觸發:
void Application_AcquireRequestState(object sender, EventArgs e) { // Session is Available here HttpContext context = HttpContext.Current; context.Session["foo"] = "foo"; }Valamas - 建議編輯:
成功地將其與 MVC 3 一起使用並避免了會話錯誤。
protected void Application_AcquireRequestState(object sender, EventArgs e) { HttpContext context = HttpContext.Current; if (context != null && context.Session != null) { context.Session["foo"] = "foo"; } }