NET MVC3.0 website Statistics login Certified online number of people

Source: Internet
Author: User
Tags httpcontext

NET MVC3.0 website Statistics login Certified online number of people

Objective

For a Web site, counting the number of people online is a very important job. Usually also found that a lot of web forums and so on have online number of display. For a website with a large number of people online, it is also a great thing for users to see this number. Because before for this knowledge point just know, and did not know, these two days chance to see again, so I put together a simple version, also convenient for everyone to give advice.

This article mainly through application and session global to statistics online number, temporarily only statistics login verified. The approximate scenario for implementation is as follows:

1, when the global application starts, application["Count"]=0; initialization statistics online number 0

2, processing a simple form login authentication, at the time of login to the global variable application["count" for the cumulative 1 operation. At the same time, write the session value when logging in, set a valid time of 1 minutes (for how long as needed, this is only used as a test).

3, in the session failure, the user logout, the browser closes the situation to trigger, the global session function carries on to the global variable application["count" the operation to reduce 1.

Body

First step: Create a new ASP. NET MVC3.0 Web project and select the Razor engine. Set the initial number of people online. Locate Application_Start in the Global.asax file.

        protected void Application_Start ()        {            application["count"] = 0;   Initialize the online population at the first start of the application at 0            arearegistration.registerallareas ();            Registerglobalfilters (globalfilters.filters);            RegisterRoutes (routetable.routes);        }

The second step: simple modification of login verification, authentication success, write session value, and the number of online processing plus 1.

 [HttpPost] public actionresult LogOn (Logonmodel model, string returnUrl) {if (model State.isvalid)////Simple Authentication is the login valid {//session mark to write session value and set the valid time System.Web.HttpContext . CURRENT.SESSION.ADD ("SessionID", Guid.NewGuid ().                ToString ());                System.Web.HttpContext.Current.Session.Timeout = 5; Login successful, add 1 processing to the online number global variable system.web.httpcontext.current.application["count"] = Convert.ToInt32 (System.Web.Ht                tpcontext.current.application["Count"]) + 1; if (request.querystring["RETURNURL"]! = null) {FORMSAUTHENTICATION.REDIRECTFROMLOGINPAG E (model.                UserName, false); } else {Formsauthentication.setauthcookie (model.                    UserName, false);                Return redirecttoaction ("Index", "Home");        }} return View (model); }

Step three: Add Session_End in the global Global.asax file, that is, Session end (logout, browser off, session expiration expires)

        protected void Session_End (object sender, EventArgs e)        {            application.lock ();            application["Count"] = Convert.ToInt32 (application["Count"])-1;            Application.UnLock ();        }

This is to remember to lock processing, because there may be concurrency problems. When you log in, you also need to lock and unlock the processing, the above is not added.

Fourth step: The log out action is handled as follows:

        Public ActionResult LogOff ()        {            formsauthentication.signout ();            System.Web.HttpContext.Current.Session.Abandon ();//Cancel the current session            return Redirecttoaction ("Index", "Home");        }

Cancels the current session so that the global session_end function defined above is triggered.

Fifth step: Add the onbeforeunload event to the body tag in the layout template.

Since this event is called when it is flushed and closed, do the following when implemented:

<script type= "Text/javascript" >    function Pageclose () {        var n = window.event.screenx-window.screenleft;        var b = n > document.documentelement.scrollwidth-20;        if (b && Window.event.clientY < 0 | | window.event.altKey) {            alert ("is off rather than refreshed");            if (' @Request. isauthenticated ' = = ' True ') {                window.location.href = '). /account/closepage ";            }        }        else {            alert ("refresh rather than Close");}    } </script>

The action called when the shutdown occurs is as follows:

        public void Closepage ()        {            formsauthentication.signout ();            System.Web.HttpContext.Current.Session.Abandon ();//Cancel current session        }

Summarize

Example download link for http://pan.baidu.com/share/link?shareid=1839967473&uk=4244870074, you can download the project, run the test can, temporarily I use IE8 test function basic implementation. For the browser to close the trigger event, compatible with the various browser issues are not considered, if you are interested in this, remember to test with IE first OH. If you find a problem you want to be notified in time to make changes to the scenario.

NET MVC3.0 website Statistics login Certified online number of people

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.