如何使用 Google Analytics .NET 客户端应用细分

How to apply segment using Google Analytics .NET 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();

我收到以下错误

An unhandled exception of type 'Google.GoogleApiException' occurred in Google.Apis.dll

Additional information: Google.Apis.Requests.RequestError

Invalid value 'users::condition::ga:dimension2!=0,ga:sessionCount>=2,ga:daysSinceLastSession<=14'. Values must match the following regular expression: 'ga:.+' [400]

Errors [

Message[Invalid value 'users::condition::ga:dimension2!=0,ga:sessionCount>=2,ga:daysSinceLastSession<=14'. Values must match the following regular expression: 'ga:.+'] Location[metrics - parameter] Reason[invalidParameter] Domain[global]

]

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

感谢 找到了解决方案。请求中有一个 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();