【问题标题】:How to I read the number of LIVE users from Google Analytics in my .NET MVC application?如何在我的 .NET MVC 应用程序中从 Google Analytics 读取 LIVE 用户数?
【发布时间】:2017-11-14 10:24:21
【问题描述】:

我有一个 ASP.NET MVC Web 应用程序。我想显示一个网站的 LIVE 用户数。

如何从 Google Analytics 中读取此内容?

我已经遵循了这个指南: http://www.markwemekamp.com/blog/c/how-to-read-from-google-analytics-using-c/ 但我无法让代码工作。它继续运行并提供System.NullReferenceException

所以我希望这里有更好的想法或指南的人。请只提供包含所有细节的完整指南。不是那些你不知道该怎么做的半向导。

提前致谢。

更新:

这是我正在使用的指南中的代码。我只添加了日期。我正在使用 de Global.asax.cs 文件中的代码。

这段代码出现Null异常:

foreach (var x in response.Reports.First().Data.Rows)
    {
        Debug.WriteLine("The next line doesn't appear: seee.....");
        Debug.WriteLine(string.Join(", ", x.Dimensions) + "   " + string.Join(", ", x.Metrics.First().Values));
    }

代码:

protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        UnityConfig.RegisterComponents();
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        Database.SetInitializer<EFDbContext>(null);
        MethodSomethingGoogle();
    }

    public void MethodSomethingGoogle()
    {
        string todaysDate = DateTime.Now.ToString("yyyy-MM-dd");
        string tomorrowsDate = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd");

        try
        {
            var filepath = @"C:\Users\ckersten\Downloads\Dashboard-Match-Online-b2f3f0b438a1.json";
            var filepath2 = @"~\App_Data\Dashboard-Match-Online-b2f3f0b438a1.json";

            // path to the json file for the Service account
            var viewid = "109154097";    // id of the view you want to read from
            Googl

            eCredential credentials;
                using (var stream = new FileStream(filepath, FileMode.Open, FileAccess.Read))
                {
                    string[] scopes = { AnalyticsReportingService.Scope.AnalyticsReadonly };
                    var googleCredential = GoogleCredential.FromStream(stream);
                    credentials = googleCredential.CreateScoped(scopes);
                }

                var reportingService = new AnalyticsReportingService(
                    new BaseClientService.Initializer
                    {
                        HttpClientInitializer = credentials
                    });
                var dateRange = new DateRange
                {
                    StartDate = todaysDate,
                    EndDate = tomorrowsDate
                };
                var sessions = new Metric
                {
                    Expression = "ga:pageviews",
                    Alias = "Sessions"
                };
                var date = new Dimension { Name = "ga:date" };

                var reportRequest = new ReportRequest
                {
                    DateRanges = new List<DateRange> { dateRange },
                    Dimensions = new List<Dimension> { date },
                    Metrics = new List<Metric> { sessions },
                    ViewId = viewid
                };
                var getReportsRequest = new GetReportsRequest
                {
                    ReportRequests = new List<ReportRequest> { reportRequest }
                };
                var batchRequest = reportingService.Reports.BatchGet(getReportsRequest);
                var response = batchRequest.Execute();
                foreach (var x in response.Reports.First().Data.Rows)
                {
                    Debug.WriteLine("The next line doesn't appear: seee.....");
                    Debug.WriteLine(string.Join(", ", x.Dimensions) + "   " + string.Join(", ", x.Metrics.First().Values));
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine("Google Exception: " + e.ToString());
            }
            Debug.WriteLine(Console.ReadLine());
        }

【问题讨论】:

  • 您能提供您目前获得的代码吗?它在哪里抛出 NullReferenceException?
  • 我添加了代码。

标签: c# asp.net-mvc google-api google-analytics-api


【解决方案1】:

您的代码使用了不会为您提供实时数据的报告 API。报告 api 中的数据不会在 24 -48 小时内完成处理。

如果你想看看现在发生了什么,你应该使用实时 API。请记住,您每天每次查看只能针对 api 发出 10000 个请求。

DataResource.RealtimeResource.GetRequest request = 
service.Data.Realtime.Get(String.Format("ga:{0}", profileId), "rt:activeUsers");
RealtimeData feed = request.Execute();

foreach (List  row in realTimeData.Rows) 
{
 foreach (string col in row) 
    {
     Console.Write(col + " ");  // writes the value of the column
     }
Console.Write("\r\n");
}

我的实时 api 教程here GitHub 示例项目可以在here 找到,你也可以考虑使用service account

注意:

实时报告 API 处于有限测试阶段,仅供开发者预览。 Sign up to access the API.

【讨论】:

  • 添加我得到的第一步:“无法找到包'Google.Apis.Analytic.v3”。我安装了一个名为“Google.Apis.AnalyticsReporting.v4”的软件包,它可以工作吗?
  • 安装corect包Install-Package Google.Apis.Analytics.v3
  • “realTimeData”变量(在 de foreach 中)从何而来?我不清楚。它永远不会被分配,因此不能被使用。 List 属于哪种类型?它不能只命名为“列表”。它必须有一个类型。
  • 检查它应该引导你的教程
  • 我正在查看教程,这就是我问的原因。本页:daimto.com/googleAnalytics-realtime-csharp我不想冒犯,但我认为你犯了一个小错误。您应该将feed 更改为realTimeDataList 应该是 List&lt;string&gt;。最后一个是猜测,但它起作用了。因为此时我能够 WriteLine LIVE 用户的数量。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-16
  • 2014-09-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多