Asp.net MVC 使用者線上簡單實現及單點登陸擴充(一)

來源:互聯網
上載者:User

首先,讓我們想來思考如何?線上使用者的統計,這裡我將使用IHttpModule擴充我們的線上使用者模組。

建立我們需要的實體類

 

代碼

 public class OnlineUser
    {
        /// <summary>
        /// 登入使用者名稱
        /// </summary>
        public string UserName { get; set; }
 
        /// <summary>
        /// 登陸時間
        /// </summary>
        public DateTime LoginTime { get; set; }
        /// <summary>
        /// 最後一次啟用時間
        /// </summary>
        public DateTime LastTime { get; set; }
        /// <summary>
        /// 最後一次活動地址
        /// </summary>
        public string LastActionUrl { get; set; }
        /// <summary>
        /// 登陸IP地址
        /// </summary>
        public string LoginIp { get; set; }
        /// <summary>
        /// 是否為遊客
        /// </summary>
        public bool IsGuest { get; set; }
        /// <summary>
        /// 當前會話ID
        /// </summary>
        public string SessionID { get; set; }
    }

 

 

然後我們來實現我們的IHttpModule

 

代碼

public class UserOnlineModule : IHttpModule
    {
        #region IHttpModule 成員

        public static List<Models.OnlineUser> OnlineList = null;
        private System.Timers.Timer updateTimer;
        //線上使用者活動逾時:分鐘,預設10分鐘
        private int timeOut = 10;
        //設定計時器觸發周期:毫秒,預設1分鐘
        private double timeInterval = 60000;

        public void Init(HttpApplication context)
        {
            context.AuthenticateRequest += new EventHandler(context_AuthenticateRequest);
        }

        void context_AuthenticateRequest(object sender, EventArgs e)
        {
            if (OnlineList == null)
                OnlineList = new List<Models.OnlineUser>();

            updateTimer = new System.Timers.Timer();
            updateTimer.AutoReset = true;
            updateTimer.Elapsed += new System.Timers.ElapsedEventHandler(updateTimer_Elapsed);
            updateTimer.Interval = timeInterval;
            updateTimer.Start();
        }

        void updateTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            updateTimer.Stop();
            if (OnlineList.Count > 0)
                OnlineList.RemoveAll(p => (DateTime.Now - p.LastTime).Minutes >= timeOut);
            updateTimer.Interval = timeInterval;
            updateTimer.Start();
        }

        public void Dispose()
        {

        }
        #endregion
    }

 

 

 

對,就這麼簡單的一個IHttpModule實現,只不過是一個設定了一個簡單的定時器,每分鐘執行一次RemoveAll操作,下面我們來定義一個ActionFilter,為需要實現線上使用者記錄的頁面添加(因為實際項目中一些頁面並不需要去)

 

代碼

public class OnlineFilterAttribute : ActionFilterAttribute
    {        
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string findName = filterContext.HttpContext.User.Identity.Name;
            bool isGuest = false;

            if (filterContext.HttpContext.User.Identity.IsAuthenticated)
                findName = filterContext.HttpContext.User.Identity.Name;
            else
            {
                findName = filterContext.HttpContext.Session.SessionID.ToUpper();
                isGuest = true;
            }

            Models.OnlineUser userModel = UserOnlineModule.OnlineList.Find(p => 
                p.UserName.Equals(findName, StringComparison.CurrentCultureIgnoreCase));

            if (userModel == null)
            {
                userModel = new Models.OnlineUser();
                userModel.UserName = findName;
                userModel.LoginTime = DateTime.Now;
                userModel.LastTime = DateTime.Now;
                userModel.LoginIp = filterContext.HttpContext.Request.UserHostAddress;
                userModel.LastActionUrl = filterContext.HttpContext.Request.Url.PathAndQuery;
                userModel.SessionID = filterContext.HttpContext.Session.SessionID.ToUpper();
                userModel.IsGuest = isGuest;
                UserOnlineModule.OnlineList.Add(userModel);

            }
            else
            {
                userModel.LastTime = DateTime.Now;
                userModel.LastActionUrl = filterContext.HttpContext.Request.Url.PathAndQuery;

            }
        }

 

 

對了,忘記一個很重要的事,那就是註冊我們的IHttpModule,開啟Web.config頁面,找到<httpModules>節,添加

<add name="OnlineList" type="命名空間.UserOnlineModule"/> 

 

 

就這麼簡單的實現了線上使用者的統計,現在來看看使用

 

[OnlineFilter]
public ActionResult Index(string id)
        {
             return View();
        }

 

你可以這樣簡單的在Action上進行Filter的標註,如果你有一個Controller都需要進行線上統計,那麼你可以直接在整個Controller上標註一個就可以了。很簡單吧。

下一篇將介紹一下利用這個簡單的線上使用者實現進行單點登陸限制,其實很多朋友可能已經知道該怎麼做了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.