欢迎您访问我爱IT技术网,今天小编为你分享的编程技术是:【重构Session确实让代码简洁干净了不少】,下面是详细的分享!
重构Session确实让代码简洁干净了不少
CodeProject的这篇文章确实对我有所启迪,
http://www.codeproject.com/useritems/SessionWrapper.asp#xx1208856xx。
诚如作者所说,我们经常在ASP.NET用许多类似于下面的代码来检测Session中存储的对象,来防止Session过期后存储的变量丢失问题:
Int32nUserID=-1;
if(null!=Session["userID"]){
if(Session["userID"]isInt32){
if(0<Session["userID"]){
nUserID=(Int32)Session["userID"]
}
}
}
if(-1==nUserID)
{
thrownewApplicationException("Unexpectedsituation:userIDinvalid.");
}
this.doSomething(nUserID);
这样的代码会遍布各处。
那么,利用他的这个封装方案来做重构,确实让代码简洁干净了不少!
经过他的封装,上面的代码用这么一句话就行了:
this.doSomething(CCurrentSession.UserID)
他的类其实也很简单,如下所示:
usingSystem;
usingSystem.Web;
///--------------------------------------------------------------------
///DevelopedbyM.vanEijkel-aug2005
///[e]:marcelvaneijkel@gmail.com
///[w]:www.vaneijkel.com
namespaceVanEijkel.Web
{
///<summary>
///Wrapperclassforthesessionobject.
///Itcentralizesthelogicforretrievingandvalidationofsessioninformation.
///Byusinganapproachlikethisyouimprovetheprotectionandencapsulationofexistingcode.
///Itoffersasimple,low-risk,easymanageablewaytoimproveexistingWebApplication.
///Therfore,IcallitwebRefactoring.
///</summary>
publicclassCurrentSession
{
Constants#regionConstants
privateconstStringsMANDATORY_SESSION_KEY_NOT_FOUND_MSG="Sessionvariableexceptedbutdoesnotexist.Key={0}";
privateconstStringsMANDATORY_SESSION_VALUE_INVALID_NULL="Nonenullsessionvalueexcepted.Key={0}";
privateconstInt32nUSERID_UNKOWN=-1;
privateconstInt32nUSERID_MINIMUM=1;
privateconstStringsUSERID_INVALID="InvalidUserID:{0}.UserIDshouldbelargerthan:{1}";
#endregion
UserID#regionUserID
///<summary>
///ReturnstheuserIDasaInt32insteadofanobject.
///Thiswayyouwillgetthecompilerprotectionandintelligencesupportyouneed.
///</summary>
publicstaticInt32UserID
{
get
{
return(Int32)GetValueOrDefault(eKeys.UserID,nUSERID_UNKOWN);
}
set
{
if(nUSERID_MINIMUM>=value)
{
thrownewApplicationException(String.Format(sUSERID_INVALID,value,nUSERID_MINIMUM));
}
SetValue(eKeys.UserID,value);
}
}
#endregion
private:GetValueOrDefault(eKeyseKey,ObjectoDefaultValue)#regionprivate:GetValueOrDefault(eKeyseKey,ObjectoDefaultValue)
///<summary>
///Getsthevaluefromthesessionobject.
///</summary>
///<paramname="eKey">Thesessionkeytogetthevaluefor.</param>
///<paramname="oDefaultValue">Thedefaultvaluetouseifnovalidvaluestored.</param>
///<returns>Whenthevalueisnullorthekeydoesnotexist,
///thespecifieddefaultvalueisreturned.
///Otherwise,thevalueisreturned</returns>
privatestaticobjectGetValueOrDefault(eKeyseKey,ObjectoDefaultValue)
{
//getthevalue
objectoValue=GetValue(eKey);
//valuenotfoundornull?
if(null==oValue)
{
//returndefaultvalue
returnoDefaultValue;
}
//everythingoke:returnsessionvalue
returnoValue;
}
#endregion
private:GetMandatoryValue(eKeyseKey)#regionprivate:GetMandatoryValue(eKeyseKey)
///<summary>
///Returnsthesessionvalueforasession-keythatmustexist.
///IfthekeydoesnotexistanapplicationExceptionisthrown.
///</summary>
///<paramname="eKey">Thesession-keytoreturnthesession-valuefor.</param>
///<returns>Anone-nullvalue.</returns>
privatestaticobjectGetMandatoryValue(eKeyseKey)
{
//getthevalue
objectoValue=GetValue(eKey);
//keynotfoundorvaluenull?
if(null==oValue)
{
//throwapplicationExceptionbecauseitsapplicationlogicerror(noneCLR)
thrownewApplicationException(String.Format(sMANDATORY_SESSION_KEY_NOT_FOUND_MSG,eKey.ToString()));
}
//everythingoke:returnvalue
returnoValue;
}
#endregion
private:GetValue(eKeyseKey)#regionprivate:GetValue(eKeyseKey)
///<summary>
///Getsthesessionvaluefromthespecifiedkey.
///</summary>
///<paramname="eKey">Thekeytogetthevaluefrom</param>
///<returns>Thesessionvalueforthespecifiedsessionkey.
///Ifthekeydoesnotexist,nullisreturned.
///</returns>
privatestaticobjectGetValue(eKeyseKey)
{
returnHttpContext.Current.Items[eKey.ToString()];
}
#endregion
privateSetMandatoryValue(eKeyseKey,ObjectoValue)#regionprivateSetMandatoryValue(eKeyseKey,ObjectoValue)
privatestaticvoidSetMandatoryValue(eKeyseKey,ObjectoValue)
{
if(null==oValue)
{
thrownewApplicationException(String.Format(sMANDATORY_SESSION_VALUE_INVALID_NULL,eKey.ToString()));
}
}
#endregion
privateSetValue(eKeyseKey,ObjectoValue)#regionprivateSetValue(eKeyseKey,ObjectoValue)
///<summary>
///Storesthespecifiedsession-valuetothespecifiedsession-key.
///</summary>
///<paramname="eKey">Thekeyforthevaluetostoreinthesession.</param>
///<paramname="oValue">Thevaluetostoreinthesession</param>
privatestaticvoidSetValue(eKeyseKey,ObjectoValue)
{
HttpContext.Current.Items[eKey.ToString()]=oValue;
}
#endregion
///<summary>
///Anenumforthe
///</summary>
privateenumeKeys
{
UserID
}
}
}
以上所分享的是关于重构Session确实让代码简洁干净了不少,下面是编辑为你推荐的有价值的用户互动:
相关问题:本人新手。求大神们给个c#实现页面跳转的完整代码...
答:1,页面1 button1_Click事件中 Session[“username“]=“你的值”; Response.Redirect(”页面2.aspx”); 2、页面2 在Page_Load事件中获取Session[”username”]的值。 >>详细
相关问题:怎样用javascript代码让session立马过期
答:Session 是存放在服务器上的,过不过期取决于服务器设置,跟浏览器没什么关系,浏览器本地只是在 Cookie 里储存的 SessionID 而已。 所以方案有二,一是 js 发送一个请求告诉服务器清除该 Session,二是 js 把 Cookie 里的 SessionID 删除了(Se... >>详细
相关问题:El表达式取不到session中确实有的Map 下面代码没有...
答:map不是用数组取的,是用key取出value >>详细
- 评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)
-
