首页 新闻 会员 周边

Session["loginname"] 赋值两种方式有什么区别

2
悬赏园豆:5 [已解决问题] 解决于 2012-04-23 20:03

第一种方式:

public static void createusersession(UserSession userinfo)
        { System.Web.HttpContext.Current.Session["loginname"] = userinfo; } 

第二 种方式:

public static void createusersession(UserSession userinfo)
        { Session["loginname"] = userinfo; } 

以上两种方式有什么区别呢,好像高人喜欢用第一种方式

zhengyingcan的主页 zhengyingcan | 初学一级 | 园豆:12
提问于:2012-04-14 10:24
< >
分享
最佳答案
0

第一种方式:

System.Web.HttpContext.Current.Session == null 时,直接返回null。

第二种方式:

Session == null 时,会抛出异常。

通过ILSpy查看System.Web.UI.Page的代码可以看出:

// System.Web.UI.Page
public virtual HttpSessionState Session
{
    get
    {
        if (!this._sessionRetrieved)
        {
            this._sessionRetrieved = true;
            try
            {
                this._session = this.Context.Session;
            }
            catch
            {
            }
        }
        if (this._session == null)
        {
            throw new HttpException(SR.GetString("Session_not_enabled"));
        }
        return this._session;
    }
}

stackoverflow上有人对这个问题作出了精彩解答:

difference between session and httpcontext.current.session

收获园豆:5
dudu | 高人七级 |园豆:30994 | 2012-04-14 19:59
其他回答(6)
0

差不多

--宁静以致远-- | 园豆:364 (菜鸟二级) | 2012-04-14 10:48
0

Session 是調用頁面的方式,這個方法也是調用下面的方法。

System.Web.HttpContext.Current.Session["loginname"] = userinfo; 是調用一個靜態的方法。

無限遐想 | 园豆:3740 (老鸟四级) | 2012-04-14 12:07
0

没有什么区别,在你编写session的时候其实就是System.Web.HttpContext.Current.Session,这是他的完整写法。

rains | 园豆:860 (小虾三级) | 2012-04-14 13:34
0

同意楼上.

.Neter | 园豆:19 (初学一级) | 2012-04-14 18:21
0

学习了。。。

KivenRo | 园豆:1734 (小虾三级) | 2012-04-14 23:27
0

学习了

Death_Hacker; | 园豆:59 (初学一级) | 2012-04-15 19:42
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册