我喜欢使用
String.IsNullOrEmpty()
来检查字符串,想知道是否有类似于Session
的方法。目前我所知道的唯一方法是: var session;
if (Session["variable"] != null)
{
session = Session["variable"].ToString();
}
else
{
session = "set this";
Session["variable"] = session;
}
String.IsNullOrEmpty()
来检查字符串,想知道是否有类似于Session
的方法。目前我所知道的唯一方法是: var session;
if (Session["variable"] != null)
{
session = Session["variable"].ToString();
}
else
{
session = "set this";
Session["variable"] = session;
}
继续其他人所说的,我倾向于有两个层次:
核心层。这在几乎所有web应用程序项目中都添加了一个DLL。在这里,我有一个SessionVars类,它为Session状态的获取器/设置器做了大量的工作。它包含以下代码:
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;
}
}
注意泛型可以获取任何类型。
我还为特定类型添加了Getter / Setter,尤其是字符串类型,因为我通常更喜欢使用string.Empty而不是null来表示向用户呈现的变量。
例如:
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);
}
于是我创建了包装器来将其抽象化并提升到应用程序模型。例如,如果我们有客户详细信息:
public class CustomerInfo
{
public string Name
{
get
{
return SessionVar.GetString("CustomerInfo_Name");
}
set
{
SessionVar.SetString("CustomerInfo_Name", value);
}
}
}
这就是基本操作了。不过,你可以使用更短的语法。
sSession = (string)Session["variable"] ?? "set this";
这句话的意思是,如果会话变量为null,则将sSession设置为"set this"。
将其包装在属性中可能使事情更加优雅。
string MySessionVar
{
get{
return Session["MySessionVar"] ?? String.Empty;
}
set{
Session["MySessionVar"] = value;
}
}
那么您可以将其视为字符串。
if( String.IsNullOrEmpty( MySessionVar ) )
{
// do something
}
string mySessionVar = Session["mySessionVar"] as string;
我的建议是将Session变量提取到本地变量中,然后进行适当处理。始终假设您的Session变量可能为null,不要将它们转换为非可空类型。
如果您需要非可空类型的变量,则可以使用TryParse来获取它。
int mySessionInt;
if (!int.TryParse(mySessionVar, out mySessionInt)){
// handle the case where your session variable did not parse into the expected type
// e.g. mySessionInt = 0;
}
在我看来,最简单清晰易读的方法是:
String sVar = (string)(Session["SessionVariable"] ?? "Default Value");
这可能不是最有效的方法,因为即使在默认情况下(将字符串转换为字符串),它也会将默认字符串值转换为字符串,但如果您将其作为标准编码实践,您会发现它适用于所有数据类型,并且易于阅读。
例如(一个完全虚假的例子,但它显示了重点):
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);
我喜欢泛型选项,但除非您希望在许多地方使用它,否则似乎过度。可以修改扩展方法以特定方式扩展Session对象,以便它具有“安全”获取选项,例如Session.StringIfNull(“SessionVar”)和Session [“SessionVar”] =“myval”; 它破坏了通过Session [“SessionVar”]访问变量的简单性,但这是干净的代码,并且仍允许在需要时验证null或string。
这种方法还不假设Session变量中的对象是字符串。
if((Session["MySessionVariable"] ?? "").ToString() != "")
//More code for the Code God
所以基本上在将null变量转换为字符串之前,会将其替换为一个空字符串,因为ToString
是Object
类的一部分。
通过这种方式可以检查是否存在这样的键。
if (Session.Dictionary.ContainsKey("Sessionkey")) --> return Bool
检查是否为null是正确的做法。
处理对象类型不是正确的方法。声明严格的类型并尝试将对象强制转换为正确的类型。(并使用强制转换提示或Convert)
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 程序员而已,抱歉。
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; }
}
}
我也喜欢用属性来封装会话变量。这里的设置器很简单,但我喜欢编写获取方法,使它们只有一个出口点。为了做到这一点,我通常会在返回会话变量值之前检查其是否为空,并将其设置为默认值。
就像这样:
string Name
{
get
{
if(Session["Name"] == Null)
Session["Name"] = "Default value";
return (string)Session["Name"];
}
set { Session["Name"] = value; }
}
}
HttpSessionState
/HttpContext
的引用。您是否需要在DLL中安装MVC库以导入正确的命名空间? - seebiscuit