Asp.net MVC4 记录在线用户数及登录时长

Global.asax.cs文件

    public class MvcApplication : System.Web.HttpApplication
    {
        /// <summary>
        /// 全局事件开始
        /// </summary>
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            Application.Lock();
            Application["online"] = 0;
            Application.UnLock();
        }
        /// <summary>
        /// 全局事件结束
        /// </summary>
        protected void Application_End()
        {

        }
        /// <summary>
        /// 单个用户事件开始
        /// </summary>
        protected void Session_Start()
        {
            Application.Lock();
            int online = (int)Application["online"];
            Application["online"] = online + 1;
            Session["LoginDate"] = DateTime.Now;
            Application.UnLock();
        }
        /// <summary>
        /// 单个用户事件结束
        /// </summary>
        protected void Session_End()
        {
            Application.Lock();
            int online = (int)Application["online"];
            Application["online"] = online - 1;
            Application.UnLock();
        }
    }

Controller

        [HttpPost]
        public string LoginCheck()
        {
            if (Session["LoginDate"] == null)
            {
                Session["LoginDate"]=DateTime.Now;
                return "登录超时!";
            }
            DateTime loginDate = Convert.ToDateTime(Session["LoginDate"]);
            TimeSpan ts = DateTime.Now - loginDate; //记算当时间时与Session中保存的时间差
            string str = string.Format("已经登录{0}天{1}小时{2}分{3}秒", ts.Days, ts.Hours, ts.Minutes, ts.Seconds); //格式化输出
            return str;
        }

Html

    <span id="online"></span> 
    <span id="LoginInfo"></span>

jQuery

<script type="text/javascript">
    $(function () {
        AjaxHtml();
    });
    function AjaxHtml() {
        LoginCheck();
        OnLineCheck();
        setInterval(function () {
            LoginCheck();
        }, 10000);//登录时间显示每10秒更新一次
        setInterval(function () {
            OnLineCheck();
        }, 60000);//在线人数每60秒更新一次
    }
    function LoginCheck() {
        $.post('/LoginInfo/LoginCheck', {}, function (result) {
            $("#LoginInfo").html(result);
        });
    }
    function OnLineCheck() {
        $("#online").html('在线人数 <span style="color:red;">@System.Web.HttpContext.Current.Application["online"]</span>');
    }
</script>

 

posted @ 2015-04-29 15:42  寂静之秋  阅读(2895)  评论(0编辑  收藏  举报
哈尔滨八零网