C# Web中Session的使用

1. 关于使用之前要注意的:

  在使用session之前,一定要注意继承自System.Web.UI.Page,或在使用session时加上System.Web.HttpContext.Current:

    如:System.Web.HttpContext.Current.Session["Items"] ="xxx";

2. 在使用过程中遇到数据类型的转换,具体操作如下:

    将Session中的值转为DataTable类型:

  System.Data.DataTable dtTrendResult = (System.Data.DataTable)System.Web.HttpContext.Current.Session["xxx"];

3. Web中Session的设置与获取:

public List<DevicesModel> GetDeviceDataList(string OrderID)
{
    List<DevicesModel> dms = new List<DevicesModel>();
    if (Session["DeviceList"] == null)
    {
        DevicesModel dm1 = new DevicesModel();
        dm1.ID = 1;
        dm1.OrderID = "ORD0001";
        dm1.DeviceType = "DTM";
        dm1.Manufacturer = "CETE";
        dm1.Model = "MC-202";
        dm1.SerialNumber = "A-3042896";
        dm1.Status = "Order Saved";
        dms.Add(dm1);

        DevicesModel dm2 = new DevicesModel();
        dm2.ID = 2;
        dm2.DeviceType = "DTM";
        dm2.Manufacturer = "A&D";
        dm2.Model = "UC-DCC-C";
        dm2.SerialNumber = "B-1221-0012";
        dm2.Status = "Order Saved";
        dms.Add(dm2);

        DevicesModel dm3 = new DevicesModel();
        dm3.ID = 3;
        dm3.DeviceType = "ATG";
        dm3.Manufacturer = "A&D";
        dm3.Model = "UA-BBL-C";
        dm3.SerialNumber = "B-1001-0012";
        dm3.Status = "Order Saved";
        dms.Add(dm3);

        DevicesModel dm4 = new DevicesModel();
        dm4.ID = 4;
        dm4.OrderID = "ORD0002";
        dm4.DeviceType = "ATG";
        dm4.Manufacturer = "CETE";
        dm4.Model = "MC-232";
        dm4.SerialNumber = "";
        dm4.Status = "Order Saved";
        dms.Add(dm4);

        Session["DeviceList"] = dms;
    }
    else
    {
        dms = (List<DevicesModel>)Session["DeviceList"];
    }
    return dms;
}
View Code

4. Session的清空:

public string ClearSession()
{
    try
    {
        Session.Remove("DeviceList");
        return "OK";
    }
    catch (Exception ex)
    {
        return ex.Message.ToString();
    }
}
View Code

最后,需要注意的是构造函数中不能使用Session,这应该是所有要注意的了!

posted on 2016-06-15 18:11  Joye_Zhou  阅读(1890)  评论(0编辑  收藏  举报

导航