.NetWebApi使⽤Session
直接使⽤Session 会报错“未将对象引⽤设置到对象的实例”。
解决办法:在Global中添加如下代码
///<summary>
///打开session
///</summary>
public override void Init()
{
this.PostAuthenticateRequest += (sender, e) => HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
base.Init();
}
Session帮助类:
1public class SessionHelper
2 {
3///<summary>
4///写Session
5///</summary>
6///<typeparam name="T">Session键值的类型</typeparam> 7///<param name="key">Session的键名</param>
session下载8///<param name="value">Session的键值</param>
9public static void WriteSession<T>(string key, T value)
10 {
11if (key.Length == 0)
12return;
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>
22public 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>
31public static string GetSession(string key)
32 {
33if (key.Length == 0)
34return string.Empty;
35return HttpContext.Current.Session[key] as string;
36 }
37
38///<summary>
39///读取Session的值
40///</summary>
41///<param name="key">Session的键名</param>
42public static T GetSession<T>(string key)
43 {
44if (key.Length == 0)
45return default(T);
46return (T)HttpContext.Current.Session[key];
47 }
48
49///<summary>
50///删除指定Session
51///</summary>
52///<param name="key">Session的键名</param>
53public static void RemoveSession(string key)
54 {
55if (key.Length == 0)
56return;
57 HttpContext.Current.Session.Contents.Remove(key);
58 }
59 }
View Code
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论