在C#中确定会话variables的最佳方法是null或空?

在ASP.NET C#中检查会话variables的最佳方法是什么?

我喜欢使用String.IsNullOrEmpty作为string,并想知道是否有类似的方法的Session 。 目前我知道的唯一方法是:

  var sSession; if (Session["variable"] != null) { sSession = Session["variable"].ToString(); } else { sSession = "set this"; Session["variable"] = sSession; } 

继续从别人的话说。 我倾向于有两层:

核心层。 这是在几乎所有的Web应用程序项目中添加一个DLL 。 在这里我有一个SessionVars类,它为会话状态getters / setters做了很多工作。 它包含如下代码:

 public class SessionVar { static HttpSessionState Session { get { if (HttpContext.Current == null) throw new ApplicationException("No Http Context, No Session to Get!"); return HttpContext.Current.Session; } } public static T Get<T>(string key) { if (Session[key] == null) return default(T); else return (T)Session[key]; } public static void Set<T>(string key, T value) { Session[key] = value; } } 

请注意获得任何types的generics。

然后,我还为特定的types添加Getters / Setters,尤其是string,因为我经常喜欢使用string.Empty而不是null来显示给用户的variables。

例如:

 public static string GetString(string key) { string s = Get<string>(key); return s == null ? string.Empty : s; } public static void SetString(string key, string value) { Set<string>(key, value); } 

等等…

然后,我创build包装来抽象,并将其提交给应用程序模型。 例如,如果我们有客户的详细信息:

 public class CustomerInfo { public string Name { get { return SessionVar.GetString("CustomerInfo_Name"); } set { SessionVar.SetString("CustomerInfo_Name", value); } } } 

你明白了吧? 🙂

注:刚刚有一个想法时,添加评论接受的答案。 始终确保在使用状态服务器时将对象存储在Session中时,对象是可序列化的。 在网上农场时,使用generics来保存对象可能会非常容易,并且会一帆风顺。 我在工作的Web场上进行部署,因此在核心层中添加了对我的代码的检查,以查看对象是否可序列化,封装了Session Getters和Setter的另一个好处:)

这几乎是你如何做到这一点。 但是,可以使用更短的语法。

 sSession = (string)Session["variable"] ?? "set this"; 

这是说,如果会话variables为空,请将sSession设置为“set this”

它可能会使事情更优雅包装在一个属性。

 string MySessionVar { get{ return Session["MySessionVar"] ?? String.Empty; } set{ Session["MySessionVar"] = value; } } 

那么你可以把它当作一个string。

 if( String.IsNullOrEmpty( MySessionVar ) ) { // do something } 

c#3.0中的'as'符号非常干净。 由于所有会话variables都是可空的对象,因此您可以获取该值并将其放入您自己的typesvariables中,而不必担心引发exception。 大多数对象可以这样处理。

 string mySessionVar = Session["mySessionVar"] as string; 

我的想法是,你应该把你的会话variables变成本地variables,然后适当地处理它们。 总是假设你的会话variables可以是null,并且永远不会将它们转换为非空types。

如果你需要一个不可为空的typesvariables,那么你可以使用TryParse来获取它。

 int mySessionInt; if (!int.TryParse(mySessionVar, out mySessionInt)){ // handle the case where your session variable did not parse into the expected type // eg mySessionInt = 0; } 

在我看来,最简单的方法是清晰易读

  String sVar = (string)(Session["SessionVariable"] ?? "Default Value"); 

它可能不是最有效的方法,因为即使在默认情况下(即将string转换为string),它也会转换默认string值,但是如果将其作为标准编码实践,则会发现它适用于所有数据types,并且易于阅读。

例如(一个完全虚假的例子,但它显示了这一点):

  DateTime sDateVar = (datetime)(Session["DateValue"] ?? "2010-01-01"); Int NextYear = sDateVar.Year + 1; String Message = "The Procrastinators Club will open it's doors Jan. 1st, " + (string)(Session["OpeningDate"] ?? NextYear); 

我喜欢generics选项,但它似乎是过度杀伤,除非你希望遍布各处。 可以修改扩展方法来专门扩展Session对象,使其具有Session.StringIfNull(“SessionVar”)和Session [“SessionVar”] =“myval”这样的“安全”get选项。 它打破了通过Session [“SessionVar”]访问variables的简单性,但它是干净的代码,并且仍然允许validation是否null或如果你需要它的string。

检查没有/空是这样做的方式。

处理对象types不是要走的路。 声明一个严格的types,并尝试将该对象转换为正确的types。 (并使用投射提示或转换)

  private const string SESSION_VAR = "myString"; string sSession; if (Session[SESSION_VAR] != null) { sSession = (string)Session[SESSION_VAR]; } else { sSession = "set this"; Session[SESSION_VAR] = sSession; } 

对不起,任何违反语法,我每天VB'er

通常,我使用会话中的项目的强types属性来创buildSessionProxy。 访问这些属性的代码将检查是否为空并执行正确的types转换。 关于这一点的好处是,我的所有会议相关的项目都保存在一个地方。 我不必担心在代码的不同部分使用不同的密钥(并想知道为什么它不起作用)。 与dependency injection和嘲笑,我可以完全用unit testingtesting。 如果遵循DRY原则,还可以定义合理的默认值。

 public class SessionProxy { private HttpSessionState session; // use dependency injection for testability public SessionProxy( HttpSessionState session ) { this.session = session; //might need to throw an exception here if session is null } public DateTime LastUpdate { get { return this.session["LastUpdate"] != null ? (DateTime)this.session["LastUpdate"] : DateTime.MinValue; } set { this.session["LastUpdate"] = value; } } public string UserLastName { get { return (string)this.session["UserLastName"]; } set { this.session["UserLastName"] = value; } } } 

我也喜欢将会话variables包装在属性中。 这里的setters是微不足道的,但我喜欢写get方法,所以他们只有一个退出点。 要做到这一点,我通常检查空值,并在返回会话variables的值之前将其设置为默认值。 像这样的东西:

 string Name { get { if(Session["Name"] == Null) Session["Name"] = "Default value"; return (string)Session["Name"]; } set { Session["Name"] = value; } } 

}

此方法也不假定Sessionvariables中的对象是一个string

 if((Session["MySessionVariable"] ?? "").ToString() != "") //More code for the Code God 

所以基本上用一个空stringreplacenullvariables,然后将其转换为一个string,因为ToStringObject类的一部分

如果你知道这是一个string,你可以使用String.IsEmptyOrNull()函数。

你使用.NET 3.5吗? 创build一个IsNull扩展方法:

 public static bool IsNull(this object input) { input == null ? return true : return false; } public void Main() { object x = new object(); if(x.IsNull) { //do your thing } }