How to use Cookie in ASP. NET

  • 2021-07-18 07:46:11
  • OfStack

Cookie provides a useful way for Web applications to store user-related information. For example, when a user visits a site, you can use Cookie to save user preferences or other information so that the application can retrieve previously saved information the next time the user visits the site.

Technically speaking, Cookie is a small piece of data stored in the client (if you install XP, you can see 1 < Disk for installing Windows > :\Documents and Settings\ < User name > \ Cookies folder). When the user visits the website, the website will give the user an Cookie containing the expiration time, and the browser will store it in the folder of the client after receiving Cookie. In the future, every time a user visits a website page, the browser will find out whether there is an Cookie associated with the current website in the local Cookie folder according to the URL of the website, and if so, send it to the server together with the page request 1.

1. The knowledge of Cookie also needs to know the following points.

• ES 25EN is only a string and cannot be executed.
Most browsers stipulate that the size of Cookie should not exceed 4K, each site can save no more than 20 Cookie, and the total number of Cookie saved by all sites should not exceed 300.
Apart from Cookie, there is almost no other way to write data on the client machine (even Cookie is written by the browser). Of course, even Cookie can be disabled through browser security configuration. If you use IE browser, you can look at "Tools" → "Internet" Options → "Privacy" 1 page. Most websites today use Cookie to save some data (such as your ID) so that you can "continue" the previous configuration the next time you visit the website, so I still recommend that you don't close Cookie easily.

When using Cookie, you must be aware of its inherent security weaknesses. After all, Cookie is stored on the client. Therefore, do not keep confidential information such as user name, password, credit card number, etc. in Cookie. Do not save content in Cookie that should not be in the hands of the user or that might be controlled by others who steal Cookie.

2. Use of Cookie

Next, we will discuss how to save, read, delete and modify Cookie. First, add four buttons on the page to complete these four operations.


<asp:Button ID="btn_SaveCookie" runat="server" OnClick="btn_SaveCookie_Click" Text=" Save Cookie" />
<asp:Button ID="btn_ReadCookie" runat="server" Text=" Read Cookie" OnClick="btn_ReadCookie_Click" />
<asp:Button ID="btn_ModifyCookie" runat="server" OnClick="btn_ModifyCookie_Click" Text=" Modify Cookie" />
<asp:Button ID="btn_DelCookie" runat="server" Text=" Delete Cookie" OnClick="btn_DelCookie_Click" />

The method of saving Cookie is as follows.


protected void btn_SaveCookie_Click(object sender, EventArgs e)
{
    HttpCookie SingleValueCookie = new HttpCookie("test1", " Single value Cookie");
    SingleValueCookie.Expires = DateTime.Now.AddDays(1);
    Response.Cookies.Add(SingleValueCookie);
    HttpCookie MultiValueCookie = new HttpCookie("test2");
    MultiValueCookie.Values.Add("key1", "value1");
    MultiValueCookie.Values.Add("key2", "value2");
    MultiValueCookie.Expires = DateTime.Now.AddDays(1);
    Response.Cookies.Add(MultiValueCookie);
}

We can see that one Cookie allows you to save a single value or multiple values. The HttpCookie type represents one Cookie, and the Expires attribute is used to modify the expiration time of the Cookie. For a single-valued Cookie, you can specify a value either directly in the constructor or using the Value attribute. For multivalued Cookie, you can either add subkeys and values using the Add method of the Values property or set them directly using the index of the Values property. The above code is equivalent to the following code.


protected void btn_SaveCookie_Click(object sender, EventArgs e)
{
    HttpCookie SingleValueCookie = new HttpCookie("test1");
    SingleValueCookie.Value = " Single value Cookie";
    SingleValueCookie.Expires = DateTime.Now.AddDays(1);
    Response.Cookies.Add(SingleValueCookie);
    HttpCookie MultiValueCookie = new HttpCookie("test2");
    MultiValueCookie.Values["key1"] = "value1";
    MultiValueCookie.Values["key2"] = "value2";
    MultiValueCookie.Expires = DateTime.Now.AddDays(1);
    Response.Cookies.Add(MultiValueCookie);
}

After adding values, remember to use the Response object to return Cookie back to the browser. Our server can't write Cookie directly on the client machine, but the browser does this work. Of course, the user can also set whether the browser is allowed to read and write Cookie.

The following is the operation to read Cookie.


protected void btn_ReadCookie_Click(object sender, EventArgs e)
{
    HttpCookie SingleValueCookie = Request.Cookies["test1"];
    if (SingleValueCookie != null)
    {
        Response.Write(string.Format("Key:{0} Value:{1} Expires:{2}<br/>", "test1", SingleValueCookie.Value, SingleValueCookie.Expires));
    }
 
    HttpCookie MultiValueCookie = Request.Cookies["test2"];
    if (MultiValueCookie!= null)
    {
        Response.Write(string.Format("Key:{0} Value:{1}<br/>", "test2", MultiValueCookie.Value));
        foreach (string subkey in MultiValueCookie.Values.AllKeys)
        {
            Response.Write(string.Format("SubKey:{0} Value:{1} Expires:{2}<br/>", subkey, MultiValueCookie.Values[subkey], MultiValueCookie.Expires));
        }
    }
}

For multivalued Cookie, we get the value of the subkey by traversing the string array returned by the AllKeys property to get all the subkeys Key. Note that before accessing Cookie, it is necessary to check whether Cookie exists at 1. Open the page, click the "Save Cookie" button first, and then click the "Read Cookie" button, resulting in the following output:

Key: test1 Value: Single value Cookie Expires: 0001-1-0: 00:00
Key:test2 Value:key1=value1 & key2=value2
SubKey:key1 Value:value1 Expires:0001-1-1 0:00:00
SubKey:key2 Value:value2 Expires:0001-1-1 0:00:00

The following points should be explained here.

We found that the expiration time of all Cookie could not be displayed normally. This is because the Cookie returned by the browser to the server does not contain an expiration time, while the Cookie returned by the server to the browser does. The expiration time only makes sense to the client browser, but not to the server.

Directly read Value of multi-valued Cookie, which will display all subkeys and subkey values using key=value method, and multiple subkeys use " & "Connect (similar to URL).

The following is the operation to delete Cookie.


protected void btn_DelCookie_Click(object sender, EventArgs e)
{
    HttpCookie SingleValueCookie = Request.Cookies["test1"];
    SingleValueCookie.Expires = DateTime.MinValue;
    Response.Cookies.Add(SingleValueCookie);
}

If you want to delete all Cookie, you can traverse the deletion.


protected void btn_DelCookie_Click(object sender, EventArgs e)
{
    foreach (string key in Request.Cookies.AllKeys)
    {
        HttpCookie cookie = Request.Cookies[key];
        cookie.Expires = DateTime.MinValue;
        Response.Cookies.Add(cookie);
    }
}

We should always remember that the server cannot delete Cookie directly, and the operation of deleting Cookie is done by the browser. Delete, in fact, is to set its expiration time to the past time, so that Cookie expires. Therefore, there are three steps for the delete operation.

1. Get the Cookie from the Request object.
2. Set the expiration time of Cookie to the past time.
3. Write Cookie back into Response.
4. Modifying Cookie is also very simple.


protected void btn_ModifyCookie_Click(object sender, EventArgs e)
{
    HttpCookie SingleValueCookie = Request.Cookies["test1"];
    SingleValueCookie.Value = " Modified single value Cookie";
    Response.Cookies.Add(SingleValueCookie);
}

3. Cookie using extensions

(1) Write Cookie


// Mode 1:
Response.Cookies["username"].value="mike";
Response.Cookies["username"].Expires=DateTime.MaxValue;
 
// Mode 2:
HttpCookie acookie = new HttpCookie("last");
acookie.Value="a";
acookie..Expires=DateTime.MaxValue;
Response.Cookies.Add(acookie);

The writing of//multivalued Cookie


// Mode 1:
Response.Cookies["userinfo1"]["name"].value="mike";
Response.Cookies["userinfo1"]["last"].value="a";
Response.Cookies["userinfo1"].Expires=DateTime.MaxValue;
 
// Mode 2:
HttpCookie cookie = new HttpCookie("userinfo1");
cookie.Values["name"]="mike";
cookie.Values["last"]="a";
cookie.Expires=DateTime.MaxValue;
//cookie.Expires = System.DateTime.Now.AddDays(1);// Set expiration time 1 Days
Response.Cookies.Add(cookie);

(2) Read Cookie
Internet Explorer Saves the site's Cookie in a file name formatted as < user > @ < domain > . txt, where < user > Is your account name.
Note: Before getting the value of Cookie, you should ensure that the Cookie does exist. Otherwise, you will get 1 exception


If (Request.Cookies["userName"]!=null)
{
    string str = Request.Cookies("userName").Value;
}
 
// Multivalued Cookie Read of
If ( Request.Cookies["userInfo1"]!=null )
{
    string name=Request.Cookies["userInfo1"]["name"];
    string last=Request.Cookies["userInfo1"]["last"];
}
 
// Read Cookie Set
for(int i = 0 ;i<Request.Cookies.Count ;i++)
{
    HttpCookie cookies = Request.Cookies;
    Response.Write("name="+cookies.Mame+"<br/>");
    if (cookies.HasKeys )// Whether there are subkeys
    {
        System.Collections.Specialized.NameValueCollection NameColl
                                             = aCookie.Values ;
        for(int j=0;j<NameColl.Count;j++)
        {
            Response.Write(" Subkey name ="+ NameColl.AllKey[j] +"<br/>");
            Response.Write(" Subkey value ="+ NameColl[j] +"<br/>");
        }
    }
    else
    {
        Response.Write("value="+cookies.Value+"<br/>");      
    }
}

When you run this code, you will see an Cookie named "ASP.NET_SessionId", and ASP. NET uses this Cookie to hold the only one identifier for your session.

(3) Delete Cookie
Set its expiration date to a past date. When the browser checks the expiration date of the Cookie, it deletes the expired Cookie.


HttpCookie cookie = new HttpCookie("userinfo1");
cookie.Expires=DateTime.Now.AddDays(-30);
Response.Cookies.Add(cookie);

(4) Modification of cookie


Response.Cookies["Info"]["user"] = "2";
Response.Cookies["Info"].Expires = DateTime.Now.AddDays(1);        Delete cookie Attributes under
HttpCookie acookie=Request.Cookies["Info"];
acookie.Values.Remove("userid");
acookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(acookie);        Delete all cookie That is, set the expiration time to now
int limit=Request.Cookies.Count - 1;
for(int i=0;i<limit;i++)
{
    acookie = Request.Cookies(i)
    acookie.Expires = DateTime.Now.AddDays(-1)
    Response.Cookies.Add(acookie)
}

-------------

If there is a master station and a level 2 domain name station and cookie is to be shared, the following settings should be added


cookie.Domain = ". Domain name ";
cookie.Path = "/";

4. Cookie Summary

Although Cookie is a simple and practical object, we should also pay attention to the working principle, size limitation and security of Cookie, which can be roughly summarized as follows.

Physical location of storage. In the Cookies folder of the client.
Type restrictions of storage. String.
The scope of state use. The context of the current request context has access to Cookie, which is independent for each user.
Size limit of storage. Each Cookie does not exceed 4K data. No more than 20 Cookie per site. The total number of Cookie of all websites shall not exceed 300.
Life cycle. Each Cookie has its own expiration time, which expires after the expiration time.
Safety and performance. Stored in the client, the security is poor. It is recommended to store sensitive data after encryption.
Advantages, disadvantages and precautions. It is convenient to associate websites and users, and save user settings for a long time.


Related articles: