2013-10-20 45 views
3

我有一個asp.net站點,在這裏我正在檢查Global.asax中的會話變量Application_BeginRequest,但它總是說object reference not set to an instance of an object,我不明白這一點,因爲我正在檢查在使用該值之前爲null的條件,但它仍然會拋出上述錯誤,但是當我在default.aspx Page_Load事件中檢查它時,它可以正常工作,沒有任何問題。什麼時候會話狀態準備好在asp.net中使用

誰能告訴什麼背後的問題,我是不是不應該使用內Application_BeginRequest

會話變量如果是的話,那又怎麼會被檢查會話值,我想要實現的是,如果用戶(如果Session [「Login」]不爲空意味着用戶登錄)並且有權訪問該頁面,然後允許他/她將他/她扔到主頁。

這是我在做什麼。
以下功能檢查,如果用戶登錄:

public static String LoggedInUser 
    { 
     get 
     { 
      if (HttpContext.Current.Session["Login"] == null) 
       return String.Empty; 
      else 
       return HttpContext.Current.Session["Login"].ToString(); 
     } 
     set 
     { 
      HttpContext.Current.Session["Login"] = value; 
     } 
    } 

以下功能檢查,如果用戶有權訪問這些頁面:

public static bool IsPageAllowed(String Pagename) 
{ 
    bool _isPageAllowed = false; 
    XmlDocument doc = new XmlDocument(); 
    doc.Load(HttpContext.Current.Server.MapPath("Pagenames.xml")); 
    if (LoggedInUser != String.Empty) 
    { 
     XmlNodeList list = doc.DocumentElement.SelectNodes("/AllPages/Pages[@user='" + GetLoggedInUserRole(Globals.LoggedInUser).ToLower() + "']/Page[contains(text(), '" + Pagename + "')]"); 
     if (list.Count > 0) 
      _isPageAllowed = true; 
    } 
    return _isPageAllowed; 
} 

及以下功能用於在Application_BeginRequest用戶基於重定向他們的權利:

if (!Globals.IsPageAllowed(rawUrl.Substring(1, rawUrl.Length - 1))) 
     { 
      Response.Redirect("default.aspx"); 
     } 

回答

6

會話狀態在適當命名爲期間和之後可用。

在獲取與當前請求關聯的請求狀態(例如會話狀態)時發生。

與描述事件的全序列可以某處[MSDN](省略http://msdn.microsoft.com/en-us/library/bb470252.aspx和其他網站,如ASP.NET Application Life Cycle

以下(許多事件的事件縮短列表,請參閱MSDN鏈接瞭解詳情):

  • BeginRequest
  • AuthenticateRequest
  • AcquireRequestState
  • PostAcquireRequestState
  • ProcessRequest方法(或異步版本IHttpAsyncHandler.BeginProcessRequest)適當的IHttpHandler類的請求。例如,如果請求是針對頁面的,則當前頁面實例將處理該請求。

注意,會話狀態不可用,直到至少AcquireRequestState(其中可能有售,如果SessionStateModule管理,以接收您的代碼之前該事件)。在BeginRequest期間,Session將無法​​使用。

請注意,如果您需要身份驗證/授權,則應使用顯式身份驗證事件(當您在會話狀態下保留身份驗證信息時,它也不適用於您的情況)。

+0

我嘗試使用Application_AcquireRequestState事件並啓動我的會話(Session [「Login」]那裏),但仍然在Application_BeginRequest中,我得到對象引用錯誤。 – Abbas

+0

@Abbas - 你有沒有檢查過我發佈的MSDN鏈接? BeginRequest事件發生在'PostAcquireSessionState'之前,所以我不確定爲什麼你期望'Session'在請求生命期早期出現。 –