zoukankan      html  css  js  c++  java
  • 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 }
    View Code

    读取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 }
    View Code

    删除指定的session的方法

    1 public static void RemoveSession(string key)
    2         {
    3             if (key.IsEmpty())
    4                 return;
    5             HttpContext.Current.Session.Contents.Remove(key);
    6         }
    View Code

    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 = strValue;
     9             HttpContext.Current.Response.AppendCookie(cookie);
    10         }
    View Code

    读取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         }
    View Code

    删除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         }
    View Code
  • 相关阅读:
    《架构之美》读后感(二)
    《架构之美》读后感(一)
    《代码大全2》阅读笔记03
    《代码大全2》阅读笔记02
    《代码大全2》阅读笔记01
    学习进度报告(十四)
    软件方法阅读笔记03
    第二讲
    1.26 十讲第一讲
    1.23
  • 原文地址:https://www.cnblogs.com/bobo-show/p/5813554.html
Copyright © 2011-2022 走看看