如何在.NET MVC应用程序中读取Google Analytics中的LIVE用户数?

时间:2017-11-14 10:24:21

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

我有一个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());
        }

1 个答案:

答案 0 :(得分:0)

您的代码使用报告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

注意:

  

Realtime Reporting API在限量版中仅供开发者预览使用。 Sign up to access the API