C # use of cookies and interaction with javascript cookies

Source: Internet
Author: User

Create:

HttpCookie cookie = new HttpCookie ("regID ");
Cookie. Value = username;
Cookie. Expires = DateTime. Now. AddDays (1 );
Response. Cookies. Add (cookie );

Create a sub-key:

Response. Cookies ["user"] ["userName"] = Server. UrlEncode (" watermelon"); // UrlEncode is used to retrieve data using javascript without garbled characters.

Or:
HttpCookie cookie = new HttpCookie ("user ");
Cookie. Values ["userName"] = "aaa"; // cookie. Values. Add ("userName", "aaa ");
Cookie. Expires = DateTime. Now. AddDays (1 );
Response. Cookies. Add (cookie) // Response. AppendCookie (cookie );

 

 

Eliminate: You cannot delete the COOKIE directly because it is saved on the user's machine after the COOKIE is created, rather than on the server.

Delete all the items as follows:

Private HttpCookie cookie = null;
Private string cookieName = string. Empty;

For (int I = 0; I <Request. Cookies. Count; I ++)
{
CookieName = Request. Cookies [I]. Name;
Cookie = new HttpCookie (cookieName );
Cookie. Expires = DateTime. Now. AddDays (-1 );
Response. Cookies. Add (cookie );
}

Delete subkeys:
HttpCookie;
Cookie = Request. Cookies ["userInfo"];
Cookie. Values. Remove ("userName ");
Cookie. Expires = DateTime. Now. AddDays (1 );
Response. Cookies. Add (cookie );

 

 

 

 

 

Use javascript to obtain the cookie:

Function get_head_cookie (c_name)
{

If (document. cookie. length> 0)
{
C_start = document. cookie. indexOf (c_name + "= ");
If (c_start! =-1)
{
C_start = c_start + c_name.length + 1;
C_end = document. cookie. indexOf (";", c_start );
If (c_end =-1)
{
C_end = document. cookie. length;
}
Return decodeURIComponent (myreplace_head (document. cookie. substring (c_start, c_end), '+ ',''));
}
}
Return null;
}

Var email = get_head_cookie ('regid ');
Var nickname = get_head_cookie ('username ');

If (email! = ''& Email! = Null & nickname! = ''& Nickname! = Null)
{
// Cookie
}
Else
{
// When the cookie is empty

}

Related Article

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.