如何使用Google Analytics.NET客户端

时间:2015-11-12 17:36:54

标签: google-analytics google-analytics-api google-api-dotnet-client

我正在尝试通过Google Analytics.NET客户端为查询应用细分,但我无法使其正常运行。这是我一直在尝试的:

var segments = analyticsService.Management.Segments.List().Execute();
var engagedTeamsSegment = segments.Items.FirstOrDefault(x => x.Name.Equals("Engaged Teams", StringComparison.OrdinalIgnoreCase));

var format = "yyyy-MM-dd";
var today = DateTime.UtcNow.Date;
var thirtyDaysAgo = today.Subtract(TimeSpan.FromDays(30));
var metrics = engagedTeamsSegment.Definition.Replace(';', ',');

var gaData = analyticsService
    .Data.Ga
    .Get($"ga:{profile.Id}", today.ToString(format), thirtyDaysAgo.ToString(format), metrics)
    .Execute();

它让我得到以下错误

  

类型' Google.GoogleApiException'未处理的例外情况发生在   Google.Apis.dll

     

其他信息:Google.Apis.Requests.RequestError

     

无效的值   '用户::条件:: GA:!DIMENSION2 = 0,GA:sessionCount> = 2,GA:daysSinceLastSession< = 14&#39 ;.   值必须与以下正则表达式匹配:' ga:。+' [400]

     

错误[

     

消息[无效值   '用户::条件:: GA:!DIMENSION2 = 0,GA:sessionCount> = 2,GA:daysSinceLastSession< = 14&#39 ;.   值必须与以下正则表达式匹配:' ga:。+']   位置[metrics - parameter]原因[invalidParameter]域[global]

     

我可能做错了但不确定是什么。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

感谢this question找到解决方案。请求中有Segment个参数。下面的代码做了诀窍:

var segments = analyticsService.Management.Segments.List().Execute();
var engagedTeamsSegment = segments.Items.FirstOrDefault(x => x.Name.Equals("Engaged Teams", StringComparison.OrdinalIgnoreCase));

var format = "yyyy-MM-dd";
var today = DateTime.UtcNow.Date;
var thirtyDaysAgo = today.Subtract(TimeSpan.FromDays(30));

var gaDataRequest = analyticsService
    .Data.Ga
    .Get($"ga:{profile.Id}", thirtyDaysAgo.ToString(format), today.ToString(format), "ga:users");

gaDataRequest.Segment = engagedTeamsSegment.Definition;

var gaData = gaDataRequest.Execute();