asp.net 中使用cookie
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class ServerCookie : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button2_Click(object sender, EventArgs e)
{
//编写Cookie的一种方式
//HttpCookie cookie = new HttpCookie("username");//cookie 的名字叫username
//cookie.Value="张三";
//cookie.Expires = DateTime.Now.AddDays(1);
//Response.Cookies.Add(cookie);
//HttpCookie cookie = new HttpCookie("username");
//Response.Cookies["age"].Value = "26";
//cookie.Expires = DateTime.Now.AddDays(1);
//Response.Cookies.Add(cookie);
//另一种方式
Response.Cookies["Lastvisittime"].Value = DateTime.Now.ToString();
Response.Cookies["Lastvisittime"].Expires = DateTime.Now.AddDays(1);
}
protected void Button1_Click(object sender, EventArgs e)
{
//if (Request.Cookies["username"]!=null)
//{
// this.TextBox1.Text=Request.Cookies["username"].Value;
//}
//if (Request.Cookies["age"]!=null)
//{
// this.TextBox2.Text=Request.Cookies["age"].Value;
//}
if (Request.Cookies["Lastvisittime"] != null)
{
this.TextBox2.Text ="您最后一次登录时间是:"+ Request.Cookies["Lastvisittime"];
}
}
}
js中使用cookie:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="clientcookie.aspx.cs" Inherits="clientcookie" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<script type="text/javascript">
function SetCookie() {
var cvalue = prompt('请输入您的姓名');
var thedate = new Date();
thedate.setDate(thedate.getDate()+1);
document.cookie = 'username=' + cvalue + ';Expires=' + thedate.toGMTString();
}
function GetCookie() {
if (document.cookie.length > 0) {
var index = document.cookie.indexOf(';');
if (index == -1) {
index = document.cookie.length;
}
var cvalue = document.cookie.substr(9, index - 9);
return cvalue;
}
else {
return "";
}
}
function CheckCookie() {
var cvalue = GetCookie();
if (cvalue != null && cvalue != "") {
document.write(cvalue + '欢迎您再次光临');
}
else {
SetCookie();
}
}
</script>
</head>
<body οnlοad="CheckCookie();">
<form id="form1" runat="server">
<div>
<input type="button" value="写cookie" οnclick="SetCookie()" />
<input type="button" value="读cookie" οnclick="GetCookie()" />
</div>
</form>
</body>
</html>