如何计算访问网站的次数和MVC中的在线用户数

时间:2015-10-29 16:30:09

标签: asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 razor

我需要了解网站访问次数以及网站用户数量。

我的代码是:

Global.asax中

 protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);


        // Code that runs on application startup
        Application["SiteVisitedCounter"] = 0;
        //to check how many users have currently opened our site write the following line
        Application["OnlineUserCounter"] = 0;
    }

    void Session_Start(object sender, EventArgs e)
    {
        // Code that runs when a new session is started
        Application.Lock();
        Application["SiteVisitedCounter"] = Convert.ToInt32(Application["SiteVisitedCounter"]) + 1;
        //to check how many users have currently opened our site write the following line
        Application["OnlineUserCounter"] = Convert.ToInt32(Application["OnlineUserCounter"]) + 1;
        Application.UnLock();
    }

    void Session_End(object sender, EventArgs e)
    {
        // Code that runs when a session ends.
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer
        // or SQLServer, the event is not raised.
        Application.Lock();
        Application["OnlineUserCounter"] = Convert.ToInt32(Application["OnlineUserCounter"]) - 1;
        Application.UnLock();
    }

HomeController类包含以下代码。 我在System.Net.Mime.MediaTypeNames.Application上出错了。

   [HttpGet]
   public ActionResult Index()
    {
        ViewBag.noofsitesvisited = "No of times site visited=" + System.Net.Mime.MediaTypeNames.Application["SiteVisitedCounter"].ToString();
        ViewBag.onlineusers = "No of users online on the site=" + System.Net.Mime.MediaTypeNames.Application["OnlineUserCounter"].ToString();
    }

2 个答案:

答案 0 :(得分:1)

您需要更改控制器中的代码,如下所示:

         <td bgcolor="#E3E3ED" widtd = "50PS">Id</td>
     <td bgcolor="#E3E3ED" widtd = "40PX"> Release&nbsp;</td>
     <td bgcolor="#E3E3ED" widtd = "90PX">Component&nbsp;</td>
     <td bgcolor="#E3E3ED" widtd = "40PX">Status&nbsp;</td>
     <td bgcolor="#E3E3ED" widtd = "10px">MBC&nbsp; </td>
     <td bgcolor="#E3E3ED" widtd = "10px">MSC&nbsp;</td>
     <td bgcolor="#E3E3ED" widtd = "10px">IBS&nbsp;</td>
     <td bgcolor="#E3E3ED" widtd = "10px">S0&nbsp;></td>

在MVC中,应用程序变量可通过HttpContext访问

答案 1 :(得分:1)

你不想这样做。一,从网络环境中的任何全局读取和写入数据是危险的,并且从一开始就不可取,两个,这只会在AppPool活动时存储计数。如果服务器重新启动或者AppPool重新启动甚至只是回收,那么你的计数都会消失,你从零开始。

如果你想存储一个需要持久化的计数,那么你需要使用持久性媒介:数据库,文本文件等。这不仅通常更安全,它也是拥有真正持久性的唯一方法计数。

也就是说,为什么不使用Google Analytics或其他形式的网站分析。您不仅重新发明了轮子,而且实际的分析跟踪将更准确,并提供比您自己可以做的任何事情更有用的统计数据。

相关问题