【发布时间】: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