Write and read cookies

Source: Internet
Author: User

Cookies provide a way to store specific user information (such as historical records or user preferences) in Web applications. Cookie is a small amount of text sent back and forth between the Web server and the client together with the request and response. Web applications can read the information contained in cookies when users access websites.

The browser manages cookies on the client computer. Cookies are usedHttpResponseThe object is sent to the client, which exposesCookies. Any cookies that you want to send to the browser in a web application must be added to this set. When you write a new cookie, you must specifyNameAndValueAttribute. Each Cookie must have a unique name so that the Web application can identify it in future requests of the browser.

There are two ways to write cookies to your computer. You can directlyCookiesYou can also create a newHttpCookieObject instance and add itCookiesCollection. You must create cookies before the ASP. NET page is displayed on the client. For example, you canPage_LoadThe event processor writes a cookie, but cannotPage_UnloadWrite cookies to the event processor. For more information about the page lifecycle, see [ASP. NET page lifecycle overview].

For more information, see [Overview of ASP. NET cookies].

In CookiesSet Properties to write cookies
  • On the ASP. NET page where you want to write cookiesCookiesSet.

    The following code illustrates a cookie named usersettings and sets values for the sub-keys font and color. In addition, the expiration time is set to tomorrow.

    Response.Cookies["UserSettings"]["Font"] = "Arial";    Response.Cookies["UserSettings"]["Color"] = "Blue";    Response.Cookies["UserSettings"].Expires = DateTime.Now.AddDays(1d);    
Create HttpCookieObject instance to write cookie
  1. CreateHttpCookieType of an object instance and specify a name for it.

  2. Specify the value in the cookie subkey and set the cookie attributes.

  3. Add this cookieCookiesCollection.

    The following code example illustratesHttpCookieObject instance to display a cookie named usersettings.

    HttpCookie myCookie = new HttpCookie("UserSettings");    myCookie["Font"] = "Arial";    myCookie["Color"] = "Blue";    myCookie.Expires = DateTime.Now.AddDays(1d);    Response.Cookies.Add(myCookie);    
Robust Programming

By default, cookies are shared among all pages in the same domain, but you canPathAttribute to restrict cookies to a specific sub-directory. To allow a cookie to be accessed by all pages in all directories of the application, set it on the page in the application root directory, and do not setPathAttribute.

If you do not specify the cookie validity period, the cookie will not be continuously maintained on the customer's computer and will expire together with the user's session status.

Cookies can only be storedStringType value. You must convert any non-string value into a string before storing the cookie. Most data types are calledToStringMethod. For more information about converting data types to strings, see [ToStringMethod].

Security

Do not store confidential information (such as the user name or password) in cookies ). For more information about Cookie security, see [Overview of ASP. NET cookies].

Write and read cookies

Private void savecookie (string cookiename, string cookievalue)
{
Httpcookie mycookie = new httpcookie (cookiename );
Datetime now = datetime. now;

// Set the cookie value.
Mycookie. value = cookievalue;
// Set the cookie expiration date.
Mycookie. expires = now. addyears (1 );
If (this. response. Cookies [cookiename]! = NULL)
This. response. Cookies. Remove (cookiename );
// Add the cookie.
This. response. Cookies. Add (mycookie );
}
Private string getcookie (string cookiename)
{
Httpcookie mycookie = new httpcookie (cookiename );
Mycookie = request. Cookies [cookiename];

// Read the cookie information and display it.
If (mycookie! = NULL)
Return mycookie. value;
Else
Return NULL;
}

# Code generated by region web Form Designer
Override protected void oninit (eventargs E)
{
//
// Codegen: This call is required by the ASP. NET web form designer.
//
Initializecomponent ();
Base. oninit (E );
}

/// <Summary>
/// The designer supports the required methods-do not use the code editor to modify
/// Content of this method.
/// </Summary>
Private void initializecomponent ()
{
This. button1.click + = new system. eventhandler (this. button#click );
This. button2.click + = new system. eventhandler (this. button2_click );
This. Load + = new system. eventhandler (this. page_load );

}
# Endregion

Private void button#click (Object sender, system. eventargs E)
{
Savecookie ("mycookie", "Internet prodigal son ");
}

Private void button2_click (Object sender, system. eventargs E)
{
Response. Write (getcookie ("mycookie "));
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.