首页 > 代码库 > ASP.NET MVC5总结(三)登陆中常用技术解析之session与cookie
ASP.NET MVC5总结(三)登陆中常用技术解析之session与cookie
1.session机制
session机制是在服务器端保持状态的方案,在做系统登陆时,我们往往会用到session来存储一些用户登录的重要信息,而这些信息是不能存在cookie中的。
当访问量增多时,是会比较占用服务器性能的。
写session的方法
1 public static void WriteSession(string key, T value)2 {3 if (key.IsEmpty())4 return;5 HttpContext.Current.Session[key] = value;6 }
读取session的方法
1 public static string GetSession(string key)2 {3 if (key.IsEmpty())4 return string.Empty;5 return HttpContext.Current.Session[key] as string;6 }
删除指定的session的方法
1 public static void RemoveSession(string key)2 {3 if (key.IsEmpty())4 return;5 HttpContext.Current.Session.Contents.Remove(key);6 }
2.cookie机制
cookie机制采用的是在客户端保持状态的方案,在做系统登陆时,我们会将一下用户的基本信息存储到用户的浏览器,这时候我们将用到cookie,不过它最大能存4K的数据。
写cookie的方法
1 public static void WriteCookie(string strName, string strValue) 2 { 3 HttpCookie cookie = HttpContext.Current.Request.Cookies[strName]; 4 if (cookie == null) 5 { 6 cookie = new HttpCookie(strName); 7 } 8 cookie.Value =http://www.mamicode.com/ strValue; 9 HttpContext.Current.Response.AppendCookie(cookie);10 }
读取cookie的方法
1 public static string GetCookie(string strName)2 {3 if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)4 {5 return HttpContext.Current.Request.Cookies[strName].Value.ToString();6 }7 return "";8 }
删除cookie的方法
1 public static void RemoveCookie(string CookiesName)2 {3 HttpCookie objCookie = new HttpCookie(CookiesName.Trim());4 objCookie.Expires = DateTime.Now.AddYears(-5);5 HttpContext.Current.Response.Cookies.Add(objCookie);6 }
ASP.NET MVC5总结(三)登陆中常用技术解析之session与cookie
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。