2011-12-25 25 views
1

我將在我的應用程序中使用相當多的Session["firmaid"]。此值是在有人登錄到我的系統時設置的。如何在Session [「something」]引發NullReferenceException時自動調用方法?

如果發生了什麼,並且該值從Session中丟失,我想以某種方式擁有一個全局方法,如果它拋出一個NullReferenceException就會得到它。

我該怎麼做?

目前,我的解決方案是嘗試捕獲每次我使用Session["firmaid"],然後執行方法,如果它會拋出一個Exception將放在會話中firmaid。

有沒有更簡單的方法來做到這一點?

回答

4

而是試圖的/捕捉每次你可以換一個強類型類訪問會話,然後通過這個包裝訪問會話。

甚至寫一個擴展方法:

public static class SessionExtensions 
{ 
    public static string GetFirmaId(this HttpSessionStateBase session) 
    { 
     var firmaid = session["firmaid"] as string; 
     if (string.IsNullOrEmpty(firmaid)) 
     { 
      // TODO: call some method, take respective actions 
     }  
     return firmaid; 
    } 
} 

,然後在你的代碼,而不是:

try 
{ 
    var firmaid = Session["firmaid"]; 
    // TODO: do something with the result 
} 
catch (Exception ex) 
{ 
    // TODO: call some method, take respective actions 
} 

使用:

var firmaid = Session.GetFirmaId(); 
// TODO: do something with the result 
+0

VS不能找到HttpSessionBase,它不知道要導入什麼。你的意思是HttpSessionStateBase? – Kenci 2011-12-25 14:10:49

+0

@Kenci,這就是我的意思:'HttpSessionStateBase'。 – 2011-12-25 14:21:16

+0

你把這個類放在一個特殊的命名空間嗎? – Kenci 2011-12-25 14:22:40

4

爲什麼不乾脆寫一個靜態包裝器這個?更強大和更乾燥:

public static int GetFirmaid() { 
    if (HttpContext.Current.Session["firmaid"] == null) { 
    //do something to fall back 
    } 
    return HttpContext.Current.Session["firmaid"] 
} 

顯然,你將不得不把這個一類,你可以輕鬆地訪問,然後調用它通過:

Class.GetFirmaid() 
0

您可以創建一個動作過濾器,這將確保該屆會議[「firmaid」]的值爲:

public class SetFirmaIdAttribute : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     try 
     { 
      var firmaId = Session["firmaid"]; 
     } 
     catch (Exception ex) 
     { 
      // pass filterContext if you need access to Request, Session etc. 
      Session["firmaid"] = SetFirmaId(filterContext); 
     } 
    } 

    private int SetFirmaId(ActionExecutingContext filterContext) 
    { 
     // TODO: implement some logic 
    } 
} 

OnActionExecuting將被調用之前執行的動作,所以你會已經有Session["firmaid"]集時的動作得到執行。

一旦你實現這個屬性,你可以把它放在一個動作,控制器上,或設置爲全局。

相關問題