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

Detailed explanation of reading examples of Cookies in C#

Sep 07, 2017 pm 03:06 PM
.net cookies

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);
Copy after login

Method 2:

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

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);
Copy after login

Or:

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

Reading of cookies Take:

Read without subkey:

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

Or:

HttpContext.Current.Request.Cookies[strCookieName]
}
Copy after login

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));
Copy after login

two A way to add and read:

Add:

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

Read:

Request.Cookies["username"]
HttpContext.Current.Request.Cookies["username"]
Copy after login

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;
        }
    }
}
Copy after login


Example:

Cookie Cookie = new Cookie();
Cookie.setCookie("name", "aaa",1);//赋值
Cookie.getCookie("name");//取值
Cookie.delCookie("name");//删除
Copy after login
Copy after login
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;
        }
    }
}
Copy after login

Example:

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

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the employment prospects of C#? What are the employment prospects of C#? Oct 19, 2023 am 11:02 AM

Whether you are a beginner or an experienced professional, mastering C# will pave the way for your career.

Share several .NET open source AI and LLM related project frameworks Share several .NET open source AI and LLM related project frameworks May 06, 2024 pm 04:43 PM

The development of artificial intelligence (AI) technologies is in full swing today, and they have shown great potential and influence in various fields. Today Dayao will share with you 4 .NET open source AI model LLM related project frameworks, hoping to provide you with some reference. https://github.com/YSGStudyHards/DotNetGuide/blob/main/docs/DotNet/DotNetProjectPicks.mdSemanticKernelSemanticKernel is an open source software development kit (SDK) designed to integrate large language models (LLM) such as OpenAI, Azure

.NET performance optimization technology for developers .NET performance optimization technology for developers Sep 12, 2023 am 10:43 AM

If you are a .NET developer, you must be aware of the importance of optimizing functionality and performance in delivering high-quality software. By making expert use of the provided resources and reducing website load times, you not only create a pleasant experience for your users but also reduce infrastructure costs.

Performance differences between Java framework and .NET framework Performance differences between Java framework and .NET framework Jun 03, 2024 am 09:19 AM

In terms of high-concurrency request processing, .NETASP.NETCoreWebAPI performs better than JavaSpringMVC. The reasons include: AOT early compilation, which reduces startup time; more refined memory management, where developers are responsible for allocating and releasing object memory.

How to solve the problem of Nginx forwarding lost cookies How to solve the problem of Nginx forwarding lost cookies May 15, 2023 pm 09:10 PM

1. Lost Cookies Operation path one: http://localhost:8080/content/requestAction!showMainServiceReqDetail.action path two: http://localhost/content/requestAction!showMainServiceReqDetail.action path three: http://localhost/clp/ requestAction!showMainServiceReqDetail.action path one is direct access, path two is the same as path

C# .NET Interview Questions & Answers: Level Up Your Expertise C# .NET Interview Questions & Answers: Level Up Your Expertise Apr 07, 2025 am 12:01 AM

C#.NET interview questions and answers include basic knowledge, core concepts, and advanced usage. 1) Basic knowledge: C# is an object-oriented language developed by Microsoft and is mainly used in the .NET framework. 2) Core concepts: Delegation and events allow dynamic binding methods, and LINQ provides powerful query functions. 3) Advanced usage: Asynchronous programming improves responsiveness, and expression trees are used for dynamic code construction.

C# .NET: Exploring Core Concepts and Programming Fundamentals C# .NET: Exploring Core Concepts and Programming Fundamentals Apr 10, 2025 am 09:32 AM

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

How Scrapy uses proxy IP, user agent, and cookies to avoid anti-crawler strategies How Scrapy uses proxy IP, user agent, and cookies to avoid anti-crawler strategies Jun 23, 2023 pm 01:22 PM

With the development of web crawlers, more and more websites and servers are beginning to adopt anti-crawler strategies to prevent data from being maliciously crawled. These strategies include IP blocking, useragent detection, Cookies verification, etc. Without a corresponding response strategy, our crawlers can easily be labeled as malicious and banned. Therefore, in order to avoid this situation, we need to apply policies such as proxy IP, useragent, and cookies in the crawler program of the Scrapy framework.

See all articles