我正在为从 Analytics API 收集数据的 MVC 应用程序开发 Google Analytics Client,并且我正在尝试在 View 中显示数据。最终目标是用谷歌图表显示谷歌分析数据。
但是我不确定如何正确构建数据。每个指标都是一个带有 KeyValuePair
的字典其中指标名称是键,值是实际值。例如 ga:visitors, 3000
.我需要用它的 KeyValuePair
组织每个指标在字典中,我可以返回 View 。
例如,首先我编写了一个返回 3 个指标的控制台应用程序:
ga:visitors
ga:newVisits
ga:percentNewVisits
注意:每个指标都是一个单独的字典,带有
KeyValuePair
.例如:[ ga:visitors, 3000
]在控制台中显示数据时,代码如下所示:
Console.WriteLine("VisitorStatistics" + " " +
d.Query.StartDate + " " + "-" + " " + d.Query.EndDate + "\r\n" +
"------------------------------------------" + "\r\n" +
"Visitors:" + " " + d.TotalsForAllResults["ga:visitors"] + "\r\n" +
"New Visitors:" + " " + d.TotalsForAllResults["ga:newVisits"] + "\r\n" +
"Percent New Visitors:" + " " + d.TotalsForAllResults["ga:percentNewVisits"] +"%");
我需要在我的 MVC 4/asp.net 应用程序中显示这些数据,但我不确定如何实现这一点。所有代码都位于我的 Controller 中:
public void GAnalyticsService()
{
var serviceAccountEmail = "xxxxx.gserviceaccount.com";
var certificate = new x509Certificate2(@"C:\Users\User\Desktop\MyApp\Presentation\Nop.Web\key.p12", "notasecret", X509KeyStorageFlags.Exportable);
var credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail) {
Scopes = new[] { AnalyticsService.Scope.Analytics }
}.FromCertificate(certificate));
// Create the service.
//NopCommerce
var GoogleAnalyticsService = new AnalyticsService(new BaseClientService.Initializer() {
HttpClientInitializer = credential,
ApplicationName = "MyApp",
});
var request = GoogleAnalyticsService.Data.Ga.Get("ProfileID", "2010-02-24", "2014-02-24", "ga:visitors,ga:newVisits,ga:percentNewVisits");
//Specify some addition query parameters
request.Dimensions = "ga:visitCount";
request.Sort = "-ga:visitors";
request.MaxResults = 10000;
//Execute and fetch the results of our query
Google.Apis.Analytics.v3.Data.GaData d = request.Execute();
}
public ActionResult GAStatistics() {
//GAnalyticsService();
return View(new GAStatisticsListModel());
}
}
这是我从 Google Analytics API 收到的数据:
具有 3 个指标的总结果(每个具有 KeyValuePair 的字典)
键值对:
我只需要组织这些数据并将其显示在 View 中,只需纯数据(文本)即可。我该怎么做呢?
任何建议都会有很大帮助。
最佳答案
做了一个临时修复只是为了显示数据。它为时间beeing服务它的目的。
将 GAnalyticsService 从 void 更改为字符串方法。
返回了这个:
return "Besöksstatistik" + " " +
d.Query.StartDate + " " + "-" + " " + d.Query.EndDate + "<br/>" +
"------------------------------------------" + "<br/>" +
"Antal besökare:" + " " + d.TotalsForAllResults["ga:visitors"] + "<br/>" +
"Antal nya besökare:" + " " + d.TotalsForAllResults["ga:newVisits"] + "<br/>" +
"Procent nya besökare:" + " " + d.TotalsForAllResults["ga:percentNewVisits"] + "%".ToString();
在 View 中得到以下输出:
Besöksstatistik 2010-02-24 - 2014-02-24
------------------------------------------
Antal besökare: 343272
Antal nya besökare: 147693
Procent nya besökare: 42.54700702044485%
关于c# - 在 View 中显示 Google Analytics 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22224753/