Visual Studio .NET 2002.NET 1.0Visual Studio .NET 2003WebForms.NET 1.1.NET 3.0Visual Studio 2005.NET 2.0C# 2.0初学者C# 3.0开发Visual StudioWindows.NETASP.NETC#
如何构建简单的 Session State Sink






2.09/5 (4投票s)
允许您轻松管理会话状态,无需进行类型转换,并消除冗余代码。
引言
这段代码只是为了
- 将所有会话状态管理放在一个地方。
- 让您记住会话变量是什么。
- 简化代码。
使用代码
在页面中访问会话状态的常规方法如下所示。请注意,没有 IntelliSense,并且每次想要获取它时都需要进行类型转换。
Week week = (Week) Session["Week"];
这是我正在更改的内容。请注意,IntelliSense 可用以查看会话状态中保存了哪些变量。
Week week = SessionStateSink.Week;
Plant plant = SessionStateSink.Plant;
这是(静态)会话状态存储。
using System.Web.SessionState;
public static class SessionStateSink {
// Getting Current Session --> This is needed, since otherwise
// the static sink won't know what the session is.
private static HttpSessionState Session{
get {return HttpContext.Current.Session; }
}
// Session Variable - Auto-Create
public static Week Week {
get {
if (Session["Week"] == null) {
Session.Add("Week",new Week());
}
return (Week)Session["Week"];
}
}
//Session Variable - Get/Set
public static Plant Plant {
get {
return (Plant)Session["Plant"];
}
set{
if (Session["Plant"] == null)
Session.Add("Plant",value);
else
Session["Plant"] = value;
}
}
}
总而言之,这只是让代码更简洁、更易于管理。