.Net WebApi use Session

Direct use of the Session given "instance Object reference not set to an object."

Workaround: Add the following code in the Global

        /// <summary>
        /// 打开session
        /// </summary>
        public override void Init()
        {
            this.PostAuthenticateRequest += (sender, e) => HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
            base.Init();
        }

 

Session helper class:

 1  public class SessionHelper
 2     {
 3         /// <summary>
 4         /// 写Session
 5         /// </summary>
 6         /// <typeparam name="T">Session键值的类型</typeparam>
 7         /// <param name="key">Session的键名</param>
 8         /// <param name="value">Session的键值</param>
 9         public static void WriteSession<T>(string key, T value)
10         {
11             if (key.Length == 0 )
 12 is                  return ;
 13 is              HttpContext.Current.Session [Key] = value;
 14              HttpContext.Current.Session.Timeout = . 1 ; // period of 1 min 
15          }
 16  
. 17          ///  <Summary> 
18 is          /// write Session
 . 19          ///  </ Summary> 
20 is          ///  <param name = "key"> the Session key name </ param> 
21 is          ///  <param name = "value"> the Session keys </ param>
22         public static void WriteSession(string key, string value)
23         {
24             WriteSession<string>(key, value);
25         }
26 
27         /// <summary>
28         /// 读取Session的值
29         /// </summary>
30         /// <param name="key">Session的键名</param>        
31         public static string GetSession(string key)
32         {
33             if (key.Length == 0)
34                 return string.Empty;
35             return HttpContext.Current.Session[key] as string;
36         }
37 
38         /// <summary>
39         /// 读取Session的值
40         /// </summary>
41         /// <param name="key">Session的键名</param>        
42         public static T GetSession<T>(string key)
43         {
44             if (key.Length == 0)
45                 return default(T);
46             return (T)HttpContext.Current.Session[key];
47         }
48 
49         /// <summary>
50         /// 删除指定Session
51         /// </summary>
52         /// <param name="key">Session的键名</param>
53         public static void RemoveSession(string key)
54         {
55             if (key.Length == 0)
56                 return;
57             HttpContext.Current.Session.Contents.Remove(key);
58         }
59     }
View Code

 

Guess you like

Origin www.cnblogs.com/hahahayang/p/11014271.html