• ASP.NET基础培训 Cookie的正确利用


    Cookies有很多名字,HTTP Cookie, Web Cookie, Browser Cookie, Session Cookie等。

    在网站开发的过程中,很多初学者其实滥用了它。

    它的正确意义在于,它是在用于存储网站用户的个人数据的,什么时候存储呢?

    在客户端和服务器处于未连接状态时候存的,也就是存在本地的脱机数据。

    事实上,Cookie就是服务器发给客户端存在本地的小规模文本。

    使用场景:

    用户认证,会话认证,用户偏好设置,购物车数据,或者其它能够传输文本的业务。

    创建Cookie:

    方法1(使用HttpCookie类):

    //First Way
    HttpCookie StudentCookies = new HttpCookie("StudentCookies");
    StudentCookies.Value = TextBox1.Text;
    StudentCookies.Expires = DateTime.Now.AddHours(1);
    Response.Cookies.Add(StudentCookies);

    方法2(直接使用Response):

    //Second Way
    Response.Cookies["StudentCookies"].Value = TextBox1.Text;
    Response.Cookies["StudentCookies"].Expires = DateTime.Now.AddDays(1);

    在一个Cookie中存储多个值:

    //Writing Multiple values in single cookie
    Response.Cookies["StudentCookies"]["RollNumber"] = TextBox1.Text;
    Response.Cookies["StudentCookies"]["FirstName"] = "Abhimanyu";
    Response.Cookies["StudentCookies"]["MiddleName"] = "Kumar";
    Response.Cookies["StudentCookies"]["LastName"] = "Vatsa";
    Response.Cookies["StudentCookies"]["TotalMarks"] = "499";
    Response.Cookies["StudentCookies"].Expires = DateTime.Now.AddDays(1); 


    获取Cookie的值:

    单个值:

    string roll = Request.Cookies["StudentCookies"].Value; 

    多个值:

    //For Multiple values in single cookie
    string roll;
    roll = Request.Cookies["StudentCookies"]["RollNumber"];
    roll = roll + " " + Request.Cookies["StudentCookies"]["FirstName"];
    roll = roll + " " + Request.Cookies["StudentCookies"]["MiddleName"];
    roll = roll + " " + Request.Cookies["StudentCookies"]["LastName"];
    roll = roll + " " + Request.Cookies["StudentCookies"]["TotalMarks"];
    Label1.Text = roll; 


    删除Cookie:

    if (Request.Cookies["StudentCookies"] != null)
    {
        Response.Cookies["StudentCookies"].Expires = DateTime.Now.AddDays(-1);
        Response.Redirect("Result.aspx");  //to refresh the page
    }

    Now, fish! Can you use the cookie correctly?

    技术改变世界
  • 相关阅读:
    WOJ 1055
    做人做事
    实现Runnable接口和扩展Thread使用场景
    利用Perf4j 对java项目进行性能监控
    android画笔错位问题的解决
    IE常见的CSS的BUG(二)
    激动啊,终于诞生了,编译了属于俺自己的 JDK
    图像处理特征不变算子系列之Moravec算子(一)
    对象的动态建立和释放
    用TinyXml2读取XML文件的一个简单Demo
  • 原文地址:https://www.cnblogs.com/davidgu/p/2957231.html
Copyright © 2020-2023  润新知