Home >Backend Development >C#.Net Tutorial >Detailed explanation of reading examples of Cookies in C#

Detailed explanation of reading examples of Cookies in C#

黄舟
黄舟Original
2017-09-07 15:06:452162browse

Reading Cookies in

C

#Link:

1. Writing Cookie

1. The Name and Value attributes are set by the program, and the default values ​​​​are empty. Quote.

 2. The default value of the Domain attribute is the domain name part of the current URL, regardless of the directory in which the page that issues this cookie is located.

The default Domain attribute is www.kent.com. This attribute can be set to the required value by the program.

 3. The default value of the Path attribute is the root directory, that is, "/", no matter which directory the page that sends this cookie is in. The scope of this cookie can be further limited by setting it to a certain path by the program.

 4. Expires attribute, this attribute sets the expiration date and time of this cookie. If the validity period of the cookie is not set (default setting), a cookie can also be created, but it will not be saved on the user's hard drive, but will become part of the user's session information. The cookie will disappear when the browser is closed or the session times out. This type of cookie is called a non-persistent cookie. The cookie that stores SessionID is such a cookie. It is not stored on the hard disk, but only exists in the memory.

5. Attach the cookie to be sent to the Cookies attribute of Response to send the cookie to the client: Response.Cookies.Add(Cookie)

6. Domain attribute + Path attribute are the same All cookies are stored in a file on the client side, and cookies are separated by "*". The first line of each Cookie is the name of the Cookie, the second line is the value, the third line is a string composed of Domain attribute + Path attribute, indicating the scope of this Cookie, and the remaining lines contain the daily processing information of the Cookie, such as Expiration date and time. There is also a simple checksum in the cookie, so if the cookie name or the length of the value is changed, the browser will detect the modification and delete the cookie.

2. Read Cookie

1. The Request.Cookies attribute contains a collection of all cookies sent by the client to the server, and is only within the scope of the request URL The cookie inside will be sent to the server by the browser together with the HTTP request.

 2. The values ​​of the Name and Value attributes and subkeys are easy to read.

 3. The Domain and Path attributes cannot be read. The Domain attribute is always "" and the Path attribute is always "/". Originally these attributes were of limited use. If your page is not on the same domain as the cookie, you will not receive the cookie at all in the location of the page.

 4. The expiration date and time of the cookie cannot be read. In fact, when the browser sends Cookie information to the server, the browser does not include the expiration information. You can read the Expires property, but it always returns a date/time value of zero. The main role of the Expires attribute is to help the browser perform day-to-day management of cookie storage. From the server's perspective, the cookie either exists or it doesn't exist, so the expiration date is not useful information to the server. Therefore, the browser does not provide this information when sending the cookie. If you need a cookie's expiration date, you'll have to set it again.

3. Modify and delete Cookie

1. In fact, you cannot modify a Cookie directly. You need to create a Cookie with the same name and send the Cookie to the browser. Overwrite old cookies on the client machine.

 2. Similarly, you cannot delete a cookie directly. You can modify a cookie to let the browser delete the cookie for you. Modify the validity period of the cookie to a certain time in the past. When the browser checks the cookie When the validity period expires, the expired cookie will be deleted. Modify the validity period and delete cookies

4. The relationship between Cookie and Session

1. Session in asp.net can use two methods: cookie and cookieless. The cookieless method is to change the SessionID Put it in the URL and pass it back and forth between the client and the server without using cookies. This method will not be discussed here.

 2. In asp.net, when a client requests a URL for the first time, the server generates a SessionID for the client and sends it to the client as a non-permanent cookie.

 3. Non-permanent cookies will disappear only after the browser is closed. The Session timeout judgment is the following process:

 3.1 The first time the client accesses the server, A SessionID will be obtained and sent to the client as a non-persistent cookie.

 3.2 When accessing this URL before the browser is closed, the browser will send the SessionID to the server, and the server will maintain various statuses of the server corresponding to the client based on the SessionID (that is, the various statuses saved in the Session) values), these Sessions can be operated in web applications.

 3.3 The server maintains the expiration time of this SessionID. The Session timeout can be set in IIS. Each request will cause the server to extend the expiration time of this SessioID by a set timeout period.

 3.4 When the server discovers that a SessionID has expired, that is, a customer has not visited the site again within the set timeout period, the SessionID and all Session variables related to this SessionID will be deleted.

 3.5 Before the client's browser is closed, it does not know that the server has deleted the SessionID. The client still sends the cookie of this SessionID to the server, but at this time the server no longer recognizes the SessionID and will This user is treated as a new user and a new SessionID is assigned again.

Creation of cookies:

Create a username cookie on the client with a value of gjy and a validity period of 1 day.

Method 1:

Response.Cookies["username"].Value="zxf";
Response.Cookies["username"].Expires=DateTime.Now.AddDays(1);

Method 2:

System.Web.HttpCookie newcookie=new HttpCookie("username");
newcookie.Value="gjy";
newcookie.Expires=DateTime.Now.AddDays(1);
Response.AppendCookie(newcookie);

Create cookies with subkeys:

System.Web.HttpCookie newcookie=new HttpCookie("user");
newcookie.Values["username"]="zxf";
newcookie.Values["password"]="111";
newcookie.Expires=DateTime.Now.AddDays(1);
Response.AppendCookie(newcookie);

Or:

System.Web.HttpContext.Current.Response.Cookies.Add(Cookie);

Reading of cookies Take:

Read without subkey:

if(Request.Cookies["username"]!=null)
{
Response.Write(Server.UrlDecode(Request.Cookies["username"]));

Or:

HttpContext.Current.Request.Cookies[strCookieName]
}

Read with subkey:

if(Request.Cookies["user"]!=null)
{
Response.Write(Server.UrlDecode(Request.Cookies["user"]["username"].Value));
Response.Write(Server.UrlDecode(Request.Cookies["user"]["password"].Value));

two A way to add and read:

Add:

Response.AppendCookie(newcookie);
System.Web.HttpContext.Current.Response.Cookies.Add(Cookie);

Read:

Request.Cookies["username"]
HttpContext.Current.Request.Cookies["username"]

As long as the expiration time is not set for the cookie, the cookie will automatically expire when the browser is closed

Just delete the cookie modification time: Cookie.Expires = DateTime.Now.AddDays(-1);

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

 
public class Cookie
{
    /// <summary>
    /// Cookies赋值
    /// </summary>
    /// <param name="strName">主键</param>
    /// <param name="strValue">键值</param>
    /// <param name="strDay">有效天数</param>
    /// <returns></returns>
    public bool setCookie(string strName, string strValue, int strDay)
    {
        try
        {
            HttpCookie Cookie = new HttpCookie(strName);
            //Cookie.Domain = ".xxx.com";//当要跨域名访问的时候,给cookie指定域名即可,格式为.xxx.com
            Cookie.Expires = DateTime.Now.AddDays(strDay);
            Cookie.Value = strValue;
            System.Web.HttpContext.Current.Response.Cookies.Add(Cookie);
            return true;
        }
        catch
        {
            return false;
        }
    }

    /// <summary>
    /// 读取Cookies
    /// </summary>
    /// <param name="strName">主键</param>
    /// <returns></returns>
 
    public string getCookie(string strName)
    {
        HttpCookie Cookie = System.Web.HttpContext.Current.Request.Cookies[strName];
        if (Cookie != null)
        {
            return Cookie.Value.ToString();
        }
        else
        {
            return null;
        }
    }

    /// <summary>
    /// 删除Cookies
    /// </summary>
    /// <param name="strName">主键</param>
    /// <returns></returns>
    public bool delCookie(string strName)
    {
        try
        {
            HttpCookie Cookie = new HttpCookie(strName);
            //Cookie.Domain = ".xxx.com";//当要跨域名访问的时候,给cookie指定域名即可,格式为.xxx.com
            Cookie.Expires = DateTime.Now.AddDays(-1);
            System.Web.HttpContext.Current.Response.Cookies.Add(Cookie);
            return true;
        }
        catch
        {
            return false;
        }
    }
}


Example:

Cookie Cookie = new Cookie();
Cookie.setCookie("name", "aaa",1);//赋值
Cookie.getCookie("name");//取值
Cookie.delCookie("name");//删除
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
 
public class Cookie
{
    /// <summary>
    /// Cookies赋值
    /// </summary>
    /// <param name="strName">主键</param>
    /// <param name="strValue">键值</param>
    /// <param name="strDay">有效天数</param>
    /// <returns></returns>
    public bool setCookie(string strName, string strValue, int strDay)
    {
        try
        {
            HttpCookie Cookie = new HttpCookie(strName);
            //Cookie.Domain = ".xxx.com";//当要跨域名访问的时候,给cookie指定域名即可,格式为.xxx.com
            Cookie.Expires = DateTime.Now.AddDays(strDay);
            Cookie.Value = strValue;
            System.Web.HttpContext.Current.Response.Cookies.Add(Cookie);
            return true;
        }
        catch
        {
            return false;
        }
    }
    /// <summary>
    /// 读取Cookies
    /// </summary>
    /// <param name="strName">主键</param>
    /// <returns></returns>
 
    public string getCookie(string strName)
    {
        HttpCookie Cookie = System.Web.HttpContext.Current.Request.Cookies[strName];
        if (Cookie != null)
        {
            return Cookie.Value.ToString();
        }
        else
        {
            return null;
        }
    }
    /// <summary>
    /// 删除Cookies
    /// </summary>
    /// <param name="strName">主键</param>
    /// <returns></returns>
    public bool delCookie(string strName)
    {
        try
        {
            HttpCookie Cookie = new HttpCookie(strName);
            //Cookie.Domain = ".xxx.com";//当要跨域名访问的时候,给cookie指定域名即可,格式为.xxx.com
            Cookie.Expires = DateTime.Now.AddDays(-1);
            System.Web.HttpContext.Current.Response.Cookies.Add(Cookie);
            return true;
        }
        catch
        {
            return false;
        }
    }
}

Example:

Cookie Cookie = new Cookie();
Cookie.setCookie("name", "aaa",1);//赋值
Cookie.getCookie("name");//取值
Cookie.delCookie("name");//删除

Note:When the Cookie is garbled when it is stored in Chinese, it will be encoded in Chinese when it is stored, such as Cookie.setCookie("name", Server. UrlEncode("aaa"),1), you can decode it when reading

In addition: As long as the expiration time is not set for the cookie, the cookie will be used during browsing Automatically expires when the device is turned off

The above is the detailed content of Detailed explanation of reading examples of Cookies in C#. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn