使用应用程序状态确定活动用户 [英] Using Application State determine active users

查看:67
本文介绍了使用应用程序状态确定活动用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有与Global.asax一起添加的Asp.net网站项目。

I have Asp.net website project with Global.asax added i it.

 void Application_Start(object sender, EventArgs e) 
    {
        // Code that runs on application startup
        Application["UsersOnline"] = 0;
     
    } 
void Session_Start(object sender, EventArgs e) 
    {
     
    }

    void Session_End(object sender, EventArgs e) 
    {
        Application["UsersOnline"] = (int)Application["UsersOnline"] - 1;

    }



和登录页面;


And Login Page;

 protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
    {
        string connectionstring = WebConfigurationManager.ConnectionStrings["LocalSqlServerTracking"].ConnectionString;
        string sqlstring;
        sqlstring = "Select Name,Password,ID,SessionStateID from Employee where Name=@UserName and Password=@Password";
      
        SqlConnection con = new SqlConnection(connectionstring);
        SqlCommand command = new SqlCommand(sqlstring, con);

        command.Parameters.Add(new SqlParameter("@UserName", Login1.UserName));
        command.Parameters.Add(new SqlParameter("@Password", Login1.Password));
        System.Data.SqlClient.SqlDataReader reader;

        // open a connection with sqldatabase
        try
        {
            using (con)
            {
                con.Open();

                reader = command.ExecuteReader();

               Boolean read= reader.Read();
               online = Convert.ToInt32(reader["SessionStateID"]);
                if (read)
                {
           Session["Name"] = Login1.UserName;
                    Session["Password"] = Login1.Password;
                    Session["ID"] = reader["ID"].ToString();
                    int ID = Convert.ToInt32(Session["ID"]);
                    var matches = from p in entities.Employees
                                  where p.ID ==ID
                                  select p;
                    // Execute the query and return the entity object.
                   Employee emp = matches.Single();
                    // Change the entity object.
                    emp.SessionStateID = 0;
                    // Commit the changes back to the database.
                    entities.SaveChanges();
//Where i increase when user logged in
               Application["UsersOnline"] = (int)Application["UsersOnline"] + 1;
                    e.Authenticated = true;

                }

                else {
                   
                        Label1.Text = "User not exist";
                        e.Authenticated = false;
          
                    } 



另外webconfig文件;


Also webconfig file;

<sessionState cookieless="true" cookieName="ASP.NET_SessionId" regenerateExpiredSessionId="false" timeout="5" mode="InProc"></sessionState>




<forms loginUrl="login.aspx" defaultUrl="userHome.aspx" timeout="5" />



我正在userHome中检索应用程序状态的值(经过身份验证后我移动到thi页面);


I am retrieving value of Application state in userHome(when authenticated i move to this page);

if (!this.IsPostBack)
{
    Response.Write("Number of active sessions:"+Convert.ToString(Application["UsersOnline"]));}



如果我登录ApplicationState增加1。退出并登录将不会更改正常的应用程序状态。问题 在一定时间后应用程序状态值变为负数我无法理解。为什么我觉得Session.Timeout正在触发Session_End但是在注销后它应该是无效的。我做错了什么?我只是想看看当前的活跃用户。


If i log in ApplicationState increase by one.Logging out and logging in will not change the application state that is ok. Problem is after certain amount of time Application State value become negative which i cannot understand.Why i feel like Session.Timeout is firing the Session_End but after log out it should be ineffective.What i am doing wrong?I just want to see current active users.

推荐答案

遇到问题时,您是唯一使用该应用程序的用户吗?如果没有,有几件事可能会出错。



首先,如果多个用户同时登录或多个会话同时结束,则计数可能会变得不正确,因为多个线程可能会读取值(在任何更新之前)而不是严格的读/写序列。



此外,如果用户不存在或不登录,则计数可能出错了,因为它可能不会在那时增加,但在会话结束时系统地减少。



然后根据你存储应用程序状态的位置,应用程序可能已重新启动之间用户可能仍然登录,因此当应用程序重启可能不合适时重置计数。



如果用户输入错误的密码似乎也是如此,您将找不到任何用户,因为您的查询也会过滤密码(我希望密码在数据库中加密)。因此,我认为用户数不会增加,但会话结束时无论如何都会减少。



您总是可以在数据库中添加一些跟踪或信息帮助找出问题所在。



最好在数据库中为每个用户指定一个值,该值指示用户是否已登录,然后只计算将该标志设置为具有活跃用户的数量,因为您不需要同步原语(据我所知),您应该永远不会得到负值,因为您计算符合条件的对象。
When you have the problem, are you the only user using the application? If not, there are a couple of things that can goes wrong.

First, if multiple user log at the same time or multiple sessions ends at the same time, it might be possible that count become incorrect because multiple thread might read the values (bafore any update) instead of having a strict read/write sequence.

Also, if the user does not exists or don't log in, then the count might get wrong as it might not be incremented at that point but decremented systematically when the session ends.

Then depending on where you store the application state, the aplication might have restarted between so the user might still be logged in so resetting the count when the application restart might not not be apropriate.

It also seems that if the user enter the wrong password, you won't find any user since your query also filter the password (I hope that password are encrypted in the database). Thus, I think that the user count won't be incremented but would be decremented anyway when the session ends.

You can always add some trace or information in the database to help finding what goes wrong.

It might be best to have a value per user in the database that indicate if the user is logged in and then simply count rows that has that flag set to have the number of active user as you won't need synchronization primitives (as far as I understand) and you should never get a negative value since you count objects that match a criteria.


这篇关于使用应用程序状态确定活动用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆