我正在为一个已经存在的网站开发一个CMS.如何计算网站的点击量?请建议
本文关键字:一个 网站 计算 网站开发 存在 CMS 何计算 | 更新日期: 2023-09-27 17:54:28
我正在为一个已经存在的网站开发一个CMS,我希望添加一个计数器来计算网站上的点击次数。下面是我的代码。但这增加了计数器每次刷新页面,即使网站根本没有打开,你能告诉我我的代码中的错误吗?
namespace HGS.HGSAdmin
{
public partial class FrmEnquiry : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
int nCount = 99;
nCount = GetCounterValue();
DrawCounterValue(nCount);
}
private int GetCounterValue()
{
StreamReader ctrFile;
FileStream ctrFileW;
StreamWriter sw;
string strPath = Server.MapPath("myappcounter.txt");
string strCounterContents;
int nCounter;
if (File.Exists(strPath))
{
ctrFile = File.OpenText(strPath);
strCounterContents = ctrFile.ReadLine().ToString();
ctrFile.Close();
nCounter = Convert.ToInt32(strCounterContents);
}
else
nCounter = 0;
nCounter++;
ctrFileW = new FileStream(strPath, FileMode.OpenOrCreate, FileAccess.Write);
sw = new StreamWriter(ctrFileW);
sw.WriteLine(Convert.ToInt32(nCounter));
sw.Close();
ctrFileW.Close();
return nCounter;
}
private void DrawCounterValue(int nCounter)
{
Response.Expires = 0;
string strText = nCounter.ToString();
string strFont = "Arial";
int nSize = 10;
Bitmap bmp = null;
Graphics g = null;
try
{
Font font = new Font(strFont, nSize);
bmp = new Bitmap(1, 1, PixelFormat.Format32bppArgb);
g = Graphics.FromImage(bmp);
SizeF oSize = g.MeasureString(strText, font);
int nWidth = (int)oSize.Width;
int nHeight = (int)oSize.Height;
Color clrFG = Color.FromName("Yellow");
g.Dispose();
bmp.Dispose();
bmp = new Bitmap(nWidth, nHeight, PixelFormat.Format32bppArgb);
g = Graphics.FromImage(bmp);
g.DrawString(strText, font, new SolidBrush(clrFG), 0, 0);
MemoryStream oStream = new MemoryStream();
bmp.Save(oStream, ImageFormat.Gif);
Response.ClearContent();
Response.ContentType = "image/gif";
Response.BinaryWrite(oStream.ToArray());
Response.End();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
finally
{
if(null!= g) g.Dispose();
if(null!= bmp) bmp.Dispose();
}
}
}
}
有一种方法是写一些cookie(如果用户的Web浏览器启用了cookie)或者写一些服务器会话值,这样如果cookie或会话没有过期,您就可以检查用户以前是否访问过您的Web站点中的某些页面。
这有一个对应的:如果cookie被擦除和/或过期,和/或服务器会话被放弃,关闭或过期,一些用户将每天访问同一页面不止一次。
但是由于没有确定的方法来识别一台机器,因为你不能记录一系列ip,也不能知道用户的机器MAC,所以在这方面没有其他有效的方法。
如何实现?我认为你应该在一些进程内或数据库存储中使用哈希表或页面URL字典以及cookie/会话标识符列表。这应该允许您检查某些URL,当前请求者是否已经访问过它。
像这样(某种字典的伪代码):
"/store/product/Duke-Nukem-Forever.aspx" => { "ejojejeo39u3u39", "dhjodhodhodh", "383883dhjd3038" }
然后,在c#中:
if(!someSortOfDictionary.ContainsKey(HttpContext.Current.Request.Url))
{
someSortOfDictionary.Add(HttpContext.Current.Request.Url, new List<string>());
}
if(someSortOfDictionary[HttpContext.Current.Request.Url].Count(id => id == someCookieOrSessionId) > 0)
{
// Increase hit count!
}
另一个建议是你应该避免使用文件资源作为计数器存储。如果不止一个Web请求需要写入该文件,会发生什么情况?我认为你应该在一些数据库中增加这个计数器,它是多用户启用的。