避免频繁刷新来增加访问量
设计一个网站访问总量计数器,并避免用户通过频繁刷新、访问来增加访问量。(提示:使用Cookie对象确认用户行为)
题目是这样说的,首先老师给的提示我就不是很清楚,不知道如何确认用户行为。
==============================================================================
public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string IP = Request.UserHostAddress; Response.Cookies["ipname"].Value = IP; Response.Cookies["ipname"].Expires = DateTime.Now.AddSeconds(4); Application.Lock(); Application["counter"] = 1; if (Request.Cookies["ipname"].Value.ToString() != IP) { Application["counter"] = Convert.ToInt32(Application["counter"]) + 1; } else Application["counter"] = Convert.ToInt32(Application["counter"]) + 0; Label1.Text = "您是第" + Application["counter"] + "位访问者!"; Application.UnLock(); }}
//判断Cookie是否存在 if (Request.Cookies["ipname"] == null) { Response.Cookies["ipname"].Value = "其实没意义"; Response.Cookies["ipname"].Expires = DateTime.Now.AddSeconds(4); //初始化 Application["counter"] if (Application["counter"] == null) { Application["counter"] = 1; return; } Application.Lock(); Application["counter"] = Convert.ToInt32(Application["counter"]) + 1; Application.UnLock(); } lblAccessCount.Text = "您是第" + Application["counter"] + "位访问者!";
[解决办法]
//判断Cookie是否存在 if (Request.Cookies["ipname"] == null) { Response.Cookies["ipname"].Value = "其实没意义"; Response.Cookies["ipname"].Expires = DateTime.Now.AddSeconds(4); //初始化 Application["counter"] if (Application["counter"] == null) { Application["counter"] = 1; } else { Application.Lock(); Application["counter"] = Convert.ToInt32(Application["counter"]) + 1; Application.UnLock(); } } lblAccessCount.Text = "您是第" + Application["counter"] + "位访问者!";
[解决办法]
//判断Cookie是否存在 if (Request.Cookies["ipname"] == null) { Response.Cookies["ipname"].Value = "其实没意义"; Response.Cookies["ipname"].Expires = DateTime.Now.AddSeconds(4); //初始化 Application["counter"] if (Application["counter"] == null) { Application["counter"] = 1; } else { Application.Lock(); Application["counter"] = Convert.ToInt32(Application["counter"]) + 1; Application.UnLock(); } } lblAccessCount.Text = "您是第" + Application["counter"] + "位访问者!";