C # use cookie

Source: Internet
Author: User
Code

// Write
Protected   Void Button#click ( Object Sender, eventargs E)
{
Httpcookie = New Httpcookie ( " Mycook " ); // Initialize and set the cookie name
Datetime dt = Datetime. now;
Timespan TS =   New Timespan ( 0 , 0 , 1 , 0 , 0 ); // The expiration time is 1 minute.
Cookie. Expires = DT. Add (TS ); // Set expiration time
Cookie. Values. Add ( " Userid " , " Userid_value " );
Cookie. Values. Add ( " Userid2 " , " Userid2_value2 " );
Response. appendcookie (cookie );
// Output all content of the cookie
// Response. Write (cookie. value ); // Output: userid = userid_value & userid2 = userid2_value2
}

//Read
Protected VoidButton2_click (ObjectSender, eventargs E)
{

// Httpcookie Cokie = new httpcookie ("mycook "); // Initial tutorial
If (Request. Cookies [ " Mycook " ] ! = Null )
{
// Response. Write ("the key value in the cookie is userid:" + request. Cookies ["mycook"] ["userid"]); // Whole Line
// Response. Write ("the key value in the cookie is userid2" + request. Cookies ["mycook"] ["userid2"]);
Response. Write (request. Cookies [ " Mycook " ]. Value ); // Output all values
}
}

// Modify cookie
Protected   Void Button3_click ( Object Sender, eventargs E)
{
// Obtain the cookie object of the client.
Httpcookie COK = Request. Cookies [ " Mycook " ];

If (COK ! =   Null )
{
// Cookie modification methods
COK. Values [ " Userid " ] =   " Alter-Value " ;
COK. Values. Set ( " Userid " , " Alter-Value " );

// Add new content to cookies
COK. values. set ( " newid " , " newvalue " );
response. appendcookie (COK);
}< BR >}

//Delete cookie
Protected VoidButton4_click (ObjectSender, eventargs E)
{

Httpcookie COK = Request. Cookies [ " Mycook " ];
If (COK ! =   Null )
{
If ( ! Checkbox1.checked)
{
COK. Values. Remove ( " Userid " ); // Remove the userid key value.
}
Else
{
Timespan TS =   New Timespan ( - 1 , 0 , 0 , 0 );
COK. Expires = Datetime. Now. Add (TS ); // Delete the entire cookie, as long as the expiration time is set to the current
}
Response. appendcookie (COK );
}
}

 

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.