c#中如何判断cookie是否存在

来源:百度知道 编辑:UC知道 时间:2024/09/23 21:25:14
我做了个留言版,要求在发表留言前,必须先登录,所要在发表留言的按钮的代码中加入一段代码判断cookie是否存在.

c#中cookies的读取写入操作如下:

/////////////////////////////读取///////////////////////////////

//获得此cookie对象

HttpCookie cookie = Request.Cookies["demo"];
//检验Cookie是否已经存在
if (null == cookie) {
Response.Write("Cookie not found. <br><hr>");
}
else {
//显示Cookie的值
String strCookieValue = cookie.Value.ToString();
Response.Write("The " + strCookieName + " cookie contains: <b>"
+ strCookieValue + "</b><br><hr>");
}

/////////////////////////////写入///////////////////////////////

//创建一个新Cookie
HttpCookie cookie = new HttpCookie("demo");
//设定Cookie的值
cookie.Value = "value";
//设定cookie生命为1周,也就是7天
cookie.Expires = DateTime.Now.AddDays(7);
//添加Cookie
Response.Cookies.Add(cookie);

补充:利用cookie给密码框赋值,如果是服务器端控件 TextBox,则使用这样的方式