.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 }