日期:2014-05-20  浏览次数:20890 次

请问在asp.net 中如何创建cookie 以及如何用cookie
请问在asp.net     中如何创建cookie   以及如何用cookie

------解决方案--------------------
Visual Basic 代码
Dim MyCookie As New HttpCookie( "LastVisit ")
Dim now As DateTime = DateTime.Now

MyCookie.Value = now.ToString()
MyCookie.Expires = now.AddHours(1)

Response.Cookies.Add(MyCookie)



C# 代码
HttpCookie MyCookie = new HttpCookie( "LastVisit ");
DateTime now = DateTime.Now;

MyCookie.Value = now.ToString();
MyCookie.Expires = now.AddHours(1);

Response.Cookies.Add(MyCookie);



------解决方案--------------------
Cookies的赋值,

string UserName = "kkun ";//定义局部变量
HttpCookie cookiesUserName = new HttpCookie( "cookiesUserName ", UserName);//新建Cookies对象,并为其赋值UserName
cookiesUserName.Expires = DateTime.Now.AddYears(1);//设置该Cookeis对象的有效期,常见与网页上的保存cookies一年/一月/一周/一天
Response.SetCookie(cookiesUserName);//上面都是空话,这一步实际执行Cookies在客户端的输出,即在硬盘上输出本网站的唯一Cookies印记

检测Cookies

if (Request.Cookies[ "cookiesUserName "] == null) {
this.Label1.Text = "Cookies未设置 ";
}else{
this.Label1.Text = "Cookies已设置 ";
}

不要像在ASP中想当然的使用Cookies,典型的错误如下

Response.Write(cookiesUserName);

它也不报错,输出 "System.Web.HttpCookie "

为什么?不为什么,给你看张图就明白了

对了,输出该对象的Value属性即可,代码如

Response.Write(cookiesUseName.Value)

清除Cookes

可以使用Cookies对象的Remove/Clear方法,如

Response.Cookies.Clear();//清除所有Cookies集合

Response.Cookies.Remove(cookiesUserName);//清除名为cookisUserName的Cookies

Cookies的其它方法

Add

AllKeys

Clear

Copyto

Count

Equals

Get

GetEnumerator

GetHasCode

GetKey

GetObjectData

GetType

Keys

OnDeserialization

Remove

Set

ToString

事实证明,上述清除Cookies的方法并不可靠,帮修改如下(2007-1-11)

Response.Cookies[ "cookiesUserName "].Expires = DateTime.Now.AddDays(-1);
Response.Redirect( "/Login.aspx ", false);

----------------------------------------------

唉,高手表笑,该文章仅作为留念用,记录学习历程而已