C#程序中session的基本设置示例及清除session的方法

时间:2021-11-05 14:51:28

session的基本设置:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.SessionState;
 
namespace OAFrameWork
{
  public class CSession
  {
      public static object Get(string Key)
    {
      return HttpContext.Current.Session[Key];
    }
 
 
  public static string GetString(string Key)
    {
      object obj = HttpContext.Current.Session[Key];
      if (obj == null) return "";
      else return obj.ToString();
    }
 
 
    public static object Get(string Key,object DefaultValue)
    {
      if (HttpContext.Current.Session[Key] == null)
 
        return DefaultValue;
      else
        return HttpContext.Current.Session[Key];
 
    }
 
 
    public static object Get(string Key, object DefaultValue,Boolean CanAdd)
    {
      if (HttpContext.Current.Session[Key] == null)
      {
        if(CanAdd==true)
          HttpContext.Current.Session.Add(Key, DefaultValue);
 
        return DefaultValue;
      }
      else
        return HttpContext.Current.Session[Key];
 
    }
 
 
    public static Boolean Set(string Key,object Value)
    {
      try
      {
        if (Value == null && HttpContext.Current.Session[Key] != null)
        {
          HttpContext.Current.Session.Remove(Key);
        }
        else if (HttpContext.Current.Session[Key] == null)
          {
            HttpContext.Current.Session.Add(Key, Value);
          }
          else
          {
            HttpContext.Current.Session[Key] = Value;
          }
 
        return true;
      }
      catch (Exception ex)
      {
        CMsgBox.Show(ex.Message);
        return false;
      }
 
    }
 
 
      
    
  }
}

清除Session:

?
1
2
3
4
Session.Abandon();//清除全部Session
//清除某个Session
Session["UserName"] = null;
Session.Remove("UserName");