Simple use of cookies

Source: Internet
Author: User

One, create a new empty site, add a default.aspx

<%@ page language= "C #" autoeventwireup= "true" codefile= "Default.aspx.cs" inherits= "_default"%>

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<title></title>
<body>
<form id= "Form1" runat= "Server" >
<div>
<asp:label id= "Label1" runat= "Server" ></asp:Label>
</div>
</form>
</body>

Two, enter Default.aspx.cs add code

protected void Page_Load (object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder ();
Get a cookie from the current request
HttpCookie cookie = Request.Cookies.Get ("cookie");

Check if the cookie exists
if (cookie = = null)
{
Sb. Append ("No cookie received on the client");
Sb. Append ("Add the cookie value that can be put back <br/>");
Create a cookie
cookie = new HttpCookie ("Cookie");
Set the value of the cookie to the current time
Cookies. Value = DateTime.Now.ToString ();
Set cookies that expire within 10 minutes.
Cookies. Expires = DateTime.Now.AddMinutes (10d);
Insert a cookie in the current HTTP response
RESPONSE.COOKIES.ADD (cookie);
}
Else
{
Sb. Append ("Cookie <br/> received from the client");
Sb. Append ("Cookie name:" + cookie.) Name + "<br/>");
Sb. Append ("Cookie value:" + cookie.) Value + "<br/>");
Sb. Append ("Cookie expiry time:" +
Cookies. Expires.tostring () + "<br/>");
}
Label1.Text = sb. ToString ();
}

Third, right-click Browse, note because the first browser is not generated cookie, you need to refresh to see the effect

Simple use of cookies

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.