Application,Session,Cookie

Application:设置全局变量,所设变量在整个应用程序范围内有效。
有 Application.Lock() and Application.UnLock() 两个方法。

Session:在Asp中session要依赖于cookie才可运行,但在Asp.net中设置web.config sessionState cookieless="true"则可使session不依赖于cookie

Cookie:实例化一个cookie HttpCookie xxx=new HttpCookie("xxx")
设置单值的cookie,cookie.Value="xxx"
设置多值的cookie,cookie.Value.Add("KeyWord","value")
应用cookie Response.AppendCookie("cookiename")
读取cookie HttpCookie xxx=Request.Cookies("xxx")
设置cookie的过期时间
DateTime xxx=DateTime.Now;
TimeSpan xx=new TimeSpan(x,x,x,x) 分别为天,小时,分钟,秒
cookie.Expires=xxx.Add(xx)

代码:

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<script runat=server>
   
    //Application的应用
    public void Page_Load(Object src, EventArgs e)
    {
        Application.Lock();
        Application["User_Count"] = (Int32)Application["User_Count"] + 1;
        Application.UnLock();
        Count.Text = Application["User_Count"].ToString();

        //设置session
        Session["Name"] = "John";
        Name.Text = Session["Name"].ToString();
       
        //建立一个cookie实例,并对其赋值
        HttpCookie cookie = new HttpCookie("John");
        DateTime dt = DateTime.Now;
        TimeSpan ts = new TimeSpan(0, 0, 2, 0);
        cookie.Expires = dt.Add(ts);
       
        cookie.Values.Add("name", "John");
        cookie.Values.Add("age", "26");
        cookie.Values.Add("sex", "male");
        Response.AppendCookie(cookie);
       
        //读取cookie
        HttpCookie readcookie = Request.Cookies["John"];
        cookie1.Text = readcookie.Values["name"].ToString();
        cookie2.Text=readcookie.Values["age"].ToString();
        cookie3.Text = readcookie.Values["sex"].ToString();
       
       
    }
</script>
    <title>Application</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    The count of viewer is:<asp:Label ID="Count" ForeColor=red runat=server/><br>
    Example of Session,Name is:<asp:Label ID="Name" ForeColor=blue runat=server/>
    <br>Name:<asp:Label ID="cookie1" runat=server/><br>
    Age:<asp:Label ID="cookie2" runat=server/><br>
    Sex:<asp:Label ID="cookie3" runat=server/><br>
    </div>
    </form>
</body>
</html>

发表评论

邮箱地址不会被公开。 必填项已用*标注