I need to implement the website visitor count Usercontrol.Can any one开发者_StackOverflow中文版 help me regarding this in .Net?
You can accomplish this by using (or creating) a global.asax file.
Every time a session is started, you increment an integer, which holds the number of current visitors. Every time a session is ended, you subtract one from that integer. Next, you will have to use public properties for all pages to be able to retrieve the information.
public class Global : System.Web.HttpApplication
{
private static int totalNumberOfUsers = 0;
private static int currentNumberOfUsers = 0;
protected void Session_Start(Object sender, EventArgs e)
{
totalNumberOfUsers += 1;
currentNumberOfUsers += 1;
}
protected void Session_End(Object sender, EventArgs e)
{
currentNumberOfUsers -= 1;
}
protected void Application_End(Object sender, EventArgs e)
{ }
public static int TotalNumberOfUsers{ get { return totalNumberOfUsers; } }
public static int CurrentNumberOfUsers{ get { return currentNumberOfUsers; } }
}
Next, in your control, set the values of the global.asax file in the right labels.
private void Page_Load(object sender, System.EventArgs e)
{
int currentNumberOfUsers = HitCounters.Global.CurrentNumberOfUsers;
int totalNumberOfUsers = HitCounters.Global.TotalNumberOfUsers;
lblCurrentNumberOfUsers.Text = currentNumberOfUsers.ToString();
lblTotalNumberOfUsers.Text = totalNumberOfUsers.ToString();
}
In global.asax, do this:
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
' Code, der beim Starten der Anwendung ausgeführt wird.
' Set our user count to 0 when we start the server
Application("ActiveUsers") = 0
End Sub
Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
' Code, der beim Beenden der Anwendung ausgeführt wird.
Application("ActiveUsers") = 0
End Sub
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
' Code, der beim Starten einer neuen Sitzung ausgeführt wird.
Session.Timeout = 20
Session("Start") = Now
Application.Lock()
Application("ActiveUsers") = CInt(Application("ActiveUsers")) + 1
Application.UnLock()
End Sub
Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
' Code, der am Ende einer Sitzung ausgeführt wird.
' Hinweis: Das Session_End-Ereignis wird nur ausgelöst, wenn der sessionstate-Modus
' in der Datei "Web.config" auf InProc festgelegt wird. Wenn der Sitzungsmodus auf StateServer
' oder SQLServer festgelegt wird, wird das Ereignis nicht ausgelöst.
Application.Lock()
Application("ActiveUsers") = CInt(Application("ActiveUsers")) - 1
Application.UnLock()
End Sub
精彩评论