asp.net中的session賦值與擷取session值代碼

來源:互聯網
上載者:User

asp教程.net中的session的定義和取消有時是分散的,工作群組中的每個人定義session的時候不一樣,並且名稱有隨意性,所以做了一個session的統一管理,便於session的正常化。

//interface for session
    public interface isession {
        string tostring();
    }


2. session 類

 // managerinfo 是model中的一個類,直接繼承
// 將對象放入session中時,該對象必須是可序列化的

 [serializable]
 public class loginsession : managerinfo , isession
 {
     public loginsession(): base()
     {
         sessionid = "";
     }

     public string sessionid { get; set; }

     public override int gethashcode()
     {
         return sessionid.gethashcode();
     }

     public override string tostring()
     {
         if (!string.isnullorempty(sessionid))
             return sessionid;
         else
             return "";
     }
 }


session賦值

loginsession currentmanager = new loginsession();
currentmanager.username="admin";
currentmanager.permission="all";
currentmanager.sessionid = httpcontext.current.session.sessionid;<br>httpcontext.current.session[apps教程etting.globalsessionname] = currentmanager;
httpcontext.current.session.timeout = 200;


取得session的值

public static t getglobalsessionvalue<t>(string _propertyname)
{
    return getsessionvalue<t>(common.const.appsetting.globalsessionname, _propertyname);
}

public static t getsessionvalue<t>(string _sessionname , string _propertyname)
{
    t retval = default(t);
    string propertyname = _propertyname.tolower();

    if (convert.tostring(httpcontext.current.session[_sessionname]) != "")
    {
        object sessionobject = (object)httpcontext.current.session[_sessionname];

        if (sessionobject is isession)
        {
            propertyinfo[] propertyinfos = sessionobject.gettype().getproperties();

            foreach (var pi in propertyinfos)
            {
                string refname = pi.name.tolower();
                if (propertyname == refname)
                {
                    retval = (t)pi.getvalue(sessionobject, null);
                    break;
                }
            }                  
        }
    }

    return retval;
}

在程式中可以這樣取得session中某一項的值

string _tmpstr = utilities.getglobalsessionvalue<string>("username");
int _tmpint = utilities.getglobalsessionvalue<int>("pagesize");
model.manager = utilities.getglobalsessionvalue<manager>("managerdetail");

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.