.Net WebApi 使用Session


直接使用Session 會報錯“未將對象引用設置到對象的實例”。

解決辦法:在Global中添加如下代碼

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

 

Session幫助類:

 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                 return;
13             HttpContext.Current.Session[key] = value;
14             HttpContext.Current.Session.Timeout = 1;//有效期為1分鍾
15         }
16 
17         /// <summary>
18         /// 寫Session
19         /// </summary>
20         /// <param name="key">Session的鍵名</param>
21         /// <param name="value">Session的鍵值</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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM