cookie对象完全名字是httpcookieCollection
Response.Cookies["变量名"].Value="表达式"//设置值
username=Request.Cookies["变量名"].Value//获取值
Expires属性:有效时间,若设为0则可以实时删除Cookie变量。
Name属性:Cookie变量的名称。
Value属性:Cookie变量的值。cookie是可以删除的!
ip是可以动态的!你不用的时候,用了就是占资源
history.back(-1):直接返回当前页的上一页,数据全部消息,是个新页面
history.go(-1):也是返回当前页的上一页,不过表单里的数据全部还在
protected void Button1_Click(object sender, EventArgs e)
{
//获取IP地址
string UserIP = Request.UserHostAddress.ToString( );
int VoteID = Convert.ToInt32(RadioButtonList1.SelectedIndex.ToString( ))+1;//在此处加1
//Cookie对象声明并读取cookie,如果没投票则为null
HttpCookie cookie=Request.Cookies["userIP"];
//首先判断cookie有没有
if (cookie == null)
{
//数据库执行,修改投票
UpdateVote(VoteID);
Response.Write("<script>alert('投票成功,谢谢您的参与!')</script>");
//定义新的Cookie对象
HttpCookie newCookie = new HttpCookie("userIP");
//过期日期
newCookie.Expires = DateTime.MaxValue ;
//添加新的Cookie变量IPaddress,值为UserIP
newCookie.Values.Add("IPaddress", UserIP);
//将变量写入Cookie文件中
Response.AppendCookie(newCookie);
return;
}
else
{
//cookie有了以后判断ip是否相同
string userIP = cookie.Values["IPaddress"];
if (UserIP.Trim( ) == userIP.Trim( ))
{
Response.Write("<script>alert('一个IP地址只能投一次票,谢谢您的参与!');history.go(-1);</script>");
return;
}
else
{
HttpCookie newCookie = new HttpCookie("userIP");
newCookie.Values.Add("IPaddress", UserIP);
newCookie.Expires = DateTime.MaxValue ;
Response.AppendCookie(newCookie);
//数据库执行,修改投票
UpdateVote(VoteID);
Response.Write("<script>alert('投票成功,谢谢您的参与!')</script>");
return;
}
}
}