asp.net of cookies in C #

Source: Internet
Author: User

Write cookies
HttpCookie cookie = new HttpCookie ("info");//define Cookie object and item named info
DateTime dt = datetime.now;//Definition Time Object
TimeSpan ts=new TimeSpan (1,0,0,0)//cookie effective time, specifically check MSDN
Cookie. EXPires = dt. Add (ts);//Adding Action time
Cookie. Values.add ("User", "CXBKKK")//Add Property
Cookie. Values.add ("userid", "1203");
Response.appendcookie (cookie);//determine read cookie in write cookie
if (request.cookies["Info"]!=null)
{
String temp=convert.tostring (request.cookies["Info"). values["user") + "" +convert.tostring (request.cookies["Info"). values["userid"]);
Read it all with request.cookies["Info". Value)
if (temp== "")
{
Response.Write ("Empty");
}
Else
Response.Write (temp);
}
Else
{
Response.Write ("error");
Modify Cookies
response.cookies["Info" ["user"] = "2";
response.cookies["Info"]. Expires = DateTime.Now.AddDays (1);

Delete a property under a cookie
HttpCookie acookie=request.cookies["Info"];
Acookie. Values.remove ("userid");
Acookie. Expires = DateTime.Now.AddDays (1);
RESPONSE.COOKIES.ADD (Acookie); Delete all cookies, that is, set the expiration time for now.
int limit=request.cookies.count-1;
for (int i=0;i<limit;i++)
{
Acookie = Request.Cookies (i)
Acookie. Expires = DateTime.Now.AddDays (-1)
RESPONSE.COOKIES.ADD (Acookie)
}


Read All Cookies
HttpCookieCollection cookies;
HttpCookie Onecookie;
cookies = Request.Cookies;

string[] Cookiearray = cookies. AllKeys;
for (int i=0 i < cookiearray.length; i++)
{
Onecookie = Cookies[cookiearray[i]];
Response.Write (Onecookie.name + "-" + onecookie.value);
}

//Add single Cookies
if (Request.Browser.Cookies = = True)
{
 if (request.cookies["LastVisited1"] = = null)
 {
  httpcookie newcookie = new HttpCookie ("LastVisited1", DateTime.Now.ToString ());
  newcookie.expires = DateTime.Now.AddYears (1);
  response.cookies.add (Newcookie);
 }
 else
 {
  response.write (request.cookies["LastVisited1"). Value);
 } 
}

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.