asp.net2.0中Cookie对象的应用实例
Cookie对象的应用
本节通过一个简单的实例来介绍如何使用Cookie对象实现一个简单的网上投票系统。实例运行结果如图1和图2所示。

图1 在线投票页面

图2 查看投票结果页面
程序开发步骤如下。
(1)新建一个网站,命名为15_06,默认主页名为Default.aspx。
(2)在Default.aspx页面中添加一个Table表格,用来布局页面,然后,在该Table表格中添加一个RadioButtonList控件和两个Button控件,分别用来供用户选择投票、执行投票操作和查看投票结果功能。
(3)在该网站中添加一个Web页面,命名为Default2.aspx,该页面主要用来显示投票结果,然后在该网站的虚拟目录下新建4个记事本文件count1.txt、count2.txt、count3.txt和count4.txt,它们分别用来记录各投票选项的投票数量。
(4)程序主要代码。
为了提高代码的重用率,本系统在实现各功能之前,首先新建了一个公共类文件count.cs,该类主要用来对txt文本文件进行读取和写入操作。在count.cs类文件中,定义了两个方法readCount和addCount,其中,readCount方法用来从txt文件中读取投票数量,addCount方法用来向txt文本文件中写入投票数量。readCount方法实现代码如下:
#region 从txt文件中读取投票数量
///
/// 从txt文件中读取投票数量
///
/// 要读取的txt文件的路径及名称
/// 返回一个int类型的值,用来记录投票数量
public static int readCount(string P_str_path)
{
int P_int_count = 0;
StreamReader streamread;
streamread = File.OpenText(P_str_path);
while (streamread.Peek() != -1)
{
P_int_count = int.Parse(streamread.ReadLine());
}
streamread.Close();
return P_int_count;
}
#endregion
addCount方法实现代码如下:
#region 写入投票数量
///
/// 写入投票数量
///
/// 要操作的txt文件的路径及名称
public static void addCount(string P_str_path)
{
int P_int_count = readCount(P_str_path);
P_int_count += 1;
//将数据记录写入文件
StreamWriter streamwriter = new StreamWriter(P_str_path, False);
streamwriter.WriteLine(P_int_count);
streamwriter.Close();
}
#endregion
页面Default.aspx中,单击【投票】按钮,程序首先判断用户是否已投过票,如果用户已经投过票,则弹出信息提示框,否则,利用Cookie对象保存用户的IP地址,并弹出对话框提示用户投票成功。【投票】按钮的Click事件代码如下:
protected void Button1_Click(object sender, EventArgs e)
{
string P_str_IP = Request.UserHostAddress.ToString();
HttpCookie oldCookie = Request.Cookies["userIP"];
if (oldCookie == null)
{
if (RadioButtonList1.SelectedIndex == 0)
{
count.addCount(Server.MapPath("count1.txt"));
}
if (RadioButtonList1.SelectedIndex == 1)
{
count.addCount(Server.MapPath("count2.txt"));
}
if (RadioButtonList1.SelectedIndex == 2)
{
count.addCount(Server.MapPath("count3.txt"));
}
if (RadioButtonList1.SelectedIndex == 3)
{
count.addCount(Server.MapPath("count4.txt"));
}
Response.Write("");
//定义新的Cookie对象
HttpCookie newCookie = new HttpCookie("userIP");
newCookie.Expires = DateTime.MaxValue;
//添加新的Cookie变量IPaddress,值为P_str_IP
newCookie.Values.Add("IPaddress", P_str_IP);
//将变量写入Cookie文件中
Response.AppendCookie(newCookie);
}
else
{
string P_str_oldIP = oldCookie.Values["IPaddress"];
if (P_str_IP.Trim() == P_str_oldIP.Trim())
{
Response.Write("");
}
else
{
HttpCookie newCookie = new HttpCookie("userIP");
newCookie.Values.Add("IPaddress", P_str_IP);