在 C# 中确定会话变量为 null 或为空的最佳方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/234973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the best way to determine a session variable is null or empty in C#?
提问by craigmoliver
What is the best way to check for the existence of a session variable in ASP.NET C#?
在 ASP.NET C# 中检查会话变量是否存在的最佳方法是什么?
I like to use String.IsNullOrEmpty()
works for strings and wondered if there was a similar method for Session
. Currently the only way I know of is:
我喜欢String.IsNullOrEmpty()
对字符串使用作品,并想知道是否有类似的方法用于Session
. 目前我所知道的唯一方法是:
var session;
if (Session["variable"] != null)
{
session = Session["variable"].ToString();
}
else
{
session = "set this";
Session["variable"] = session;
}
采纳答案by Rob Cooper
To follow on from what others have said. I tend to have two layers:
从别人说的继续。我倾向于有两层:
The core layer. This is within a DLL that is added to nearly all web app projects. In this I have a SessionVars class which does the grunt work for Session state getters/setters. It contains code like the following:
核心层。这是在添加到几乎所有 Web 应用程序项目的 DLL 中。在这个我有一个 SessionVars 类,它为会话状态 getter/setter 做繁重的工作。它包含如下代码:
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;
}
}
Note the generics for getting any type.
注意获取任何类型的泛型。
I then also add Getters/Setters for specific types, especially string since I often prefer to work with string.Empty rather than null for variables presented to Users.
然后我还为特定类型添加 Getter/Setter,尤其是字符串,因为我经常更喜欢使用 string.Empty 而不是 null 来处理呈现给用户的变量。
e.g:
例如:
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);
}
And so on...
等等...
I then create wrappers to abstract that away and bring it up to the application model. For example, if we have customer details:
然后我创建包装器来抽象它并将它带到应用程序模型中。例如,如果我们有客户详细信息:
public class CustomerInfo
{
public string Name
{
get
{
return SessionVar.GetString("CustomerInfo_Name");
}
set
{
SessionVar.SetString("CustomerInfo_Name", value);
}
}
}
You get the idea right? :)
你明白吗?:)
NOTE:Just had a thought when adding a comment to the accepted answer. Always ensure objects are serializable when storing them in Session when using a state server. It can be all too easy to try and save an object using the generics when on web farm and it go boom. I deploy on a web farm at work so added checks to my code in the core layer to see if the object is serializable, another benefit of encapsulating the Session Getters and Setters :)
注意:在为已接受的答案添加评论时只是有一个想法。使用状态服务器将对象存储在 Session 中时,始终确保对象是可序列化的。在网络农场上尝试使用泛型来保存对象可能太容易了,并且它会蓬勃发展。我在工作时部署在 web 场上,因此在核心层中添加了对我的代码的检查,以查看对象是否可序列化,这是封装 Session Getters 和 Setters 的另一个好处:)
回答by Ely
That is pretty much how you do it. However, there is a shorter syntax you can use.
这几乎就是你这样做的方式。但是,您可以使用更短的语法。
sSession = (string)Session["variable"] ?? "set this";
This is saying if the session variables is null, set sSession to "set this"
这是说如果会话变量为空,则将 sSession 设置为“设置此”
回答by StingyHyman
Checking for nothing/Null is the way to do it.
检查空/空是这样做的方法。
Dealing with object types is not the way to go. Declare a strict type and try to cast the object to the correct type. (And use cast hint or 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;
}
Sorry for any syntax violations, I am a daily VB'er
抱歉有任何语法违规,我是每日 VB'er
回答by Michael Kniskern
Are you using .NET 3.5? Create an IsNull extension method:
您在使用 .NET 3.5 吗?创建一个 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
}
}
回答by Kevin Pang
If you know it's a string, you can use the String.IsEmptyOrNull() function.
如果您知道它是一个字符串,则可以使用 String.IsEmptyOrNull() 函数。
回答by Greg Ogle
It may make things more elegant to wrap it in a property.
将它包装在一个属性中可能会使事情变得更加优雅。
string MySessionVar
{
get{
return Session["MySessionVar"] ?? String.Empty;
}
set{
Session["MySessionVar"] = value;
}
}
then you can treat it as a string.
那么你可以把它当作一个字符串。
if( String.IsNullOrEmpty( MySessionVar ) )
{
// do something
}
回答by tvanfosson
Typically I create SessionProxy with strongly typed properties for items in the session. The code that accesses these properties checks for nullity and does the casting to the proper type. The nice thing about this is that all of my session related items are kept in one place. I don't have to worry about using different keys in different parts of the code (and wondering why it doesn't work). And with dependency injection and mocking I can fully test it with unit tests. If follows DRY principles and also lets me define reasonable defaults.
通常,我为会话中的项目创建具有强类型属性的 SessionProxy。访问这些属性的代码检查空值并将转换为正确的类型。这样做的好处是我所有与会话相关的项目都保存在一个地方。我不必担心在代码的不同部分使用不同的键(并想知道为什么它不起作用)。通过依赖注入和模拟,我可以使用单元测试对其进行全面测试。如果遵循 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; }
}
}
回答by Aaron Palmer
The 'as' notation in c# 3.0 is very clean. Since all session variables are nullable objects, this lets you grab the value and put it into your own typed variable without worry of throwing an exception. Most objects can be handled this way.
c# 3.0 中的“as”表示法非常简洁。由于所有会话变量都是可为空的对象,因此您可以获取值并将其放入您自己的类型化变量中,而不必担心抛出异常。大多数对象都可以通过这种方式处理。
string mySessionVar = Session["mySessionVar"] as string;
My concept is that you should pull your Session variables into local variables and then handle them appropriately. Always assume your Session variables could be null and never cast them into a non-nullable type.
我的概念是你应该将你的 Session 变量拉入局部变量,然后适当地处理它们。始终假设您的 Session 变量可以为 null,并且永远不要将它们转换为不可为 null 的类型。
If you need a non-nullable typed variable you can then use TryParse to get that.
如果您需要一个不可为空的类型变量,您可以使用 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;
}
回答by Rune Grimstad
I also like to wrap session variables in properties. The setters here are trivial, but I like to write the get methods so they have only one exit point. To do that I usually check for null and set it to a default value before returning the value of the session variable. Something like this:
我也喜欢在属性中包装会话变量。这里的 setter 是微不足道的,但我喜欢编写 get 方法,因此它们只有一个退出点。为此,我通常会检查 null 并将其设置为默认值,然后再返回会话变量的值。像这样的东西:
string Name
{
get
{
if(Session["Name"] == Null)
Session["Name"] = "Default value";
return (string)Session["Name"];
}
set { Session["Name"] = value; }
}
}
}
回答by Jon Falkner
In my opinion, the easiest way to do this that is clear and easy to read is:
在我看来,做到这一点的最简单、清晰易读的方法是:
String sVar = (string)(Session["SessionVariable"] ?? "Default Value");
It may not be the most efficient method, since it casts the default string value even in the case of the default (casting a string as string), but if you make it a standard coding practice, you find it works for all data types, and is easily readable.
它可能不是最有效的方法,因为即使在默认情况下(将字符串转换为字符串),它也会转换默认字符串值,但是如果您将其设为标准编码实践,您会发现它适用于所有数据类型,并且易于阅读。
For example (a totally bogus example, but it shows the point):
例如(一个完全虚假的例子,但它表明了这一点):
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);
I like the Generics option, but it seems like overkill unless you expect to need this all over the place. The extensions method could be modified to specifically extend the Session object so that it has a "safe" get option like Session.StringIfNull("SessionVar") and Session["SessionVar"] = "myval"; It breaks the simplicity of accessing the variable via Session["SessionVar"], but it is clean code, and still allows validating if null or if string if you need it.
我喜欢泛型选项,但它似乎有点矫枉过正,除非你希望到处都需要它。可以修改扩展方法以专门扩展 Session 对象,以便它具有“安全”获取选项,如 Session.StringIfNull("SessionVar") 和 Session["SessionVar"] = "myval"; 它打破了通过 Session["SessionVar"] 访问变量的简单性,但它是干净的代码,并且仍然允许在需要时验证是否为 null 或字符串。