【发布时间】:2017-09-26 20:53:59
【问题描述】:
我需要在我使用 asp.net 网络表单 (C#) 构建的 CMS 网络应用程序的仪表板页面中集成来自 Google Analytics 的一个非常基本的报告。
我记得我在 2015 年使用 API V3 进行的测试中能够做到这一点,但现在使用 V4,我总是收到一条错误消息,提示需要 OAuth2 进行身份验证。
我需要访问我拥有的特定分析帐户,而不是在 CMS 中导航的用户的帐户!
所以我使用 Google API Manager 提供的 API KEY。我已授予该 API 密钥所有权限。 API 密钥类似于:“d471c3ce04612f143ff0Be319aac2e17d0159add”
这里是代码
using Google.Apis.AnalyticsReporting.v4;
using Google.Apis.Services;
using System;
using Google.Apis.AnalyticsReporting.v4.Data;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.IO;
using Google.Apis.Auth.OAuth2;
using System.Threading;
using Google.Apis.Util.Store;
using System.Web;
public static class GoogleAnalyticsAPI
{
static string vmcApiKey = "<<API-KEY>>";
public static void Test()
{
AnalyticsReportingService ars = GetService(vmcApiKey);
// Create the DateRange object.
DateRange dateRange = new DateRange() { StartDate = "2017-01-01", EndDate = "2017-04-28" };
// Create the Metrics object.
Metric sessions = new Metric { Expression = "ga:sessions", Alias = "Sessions" };
//Create the Dimensions object.
Dimension browser = new Dimension { Name = "ga:browser" };
// Create the ReportRequest object.
// Create the ReportRequest object.
ReportRequest reportRequest = new ReportRequest
{
ViewId = "<<VIEW-ID>>",
DateRanges = new List<DateRange>() { dateRange },
Dimensions = new List<Dimension>() { browser },
Metrics = new List<Metric>() { sessions }
};
List<ReportRequest> requests = new List<ReportRequest>();
requests.Add(reportRequest);
// Create the GetReportsRequest object.
GetReportsRequest getReport = new GetReportsRequest() { ReportRequests = requests };
// Call the batchGet method.
GetReportsResponse response = ars.Reports.BatchGet(getReport).Execute();
}
public static AnalyticsReportingService GetService(string apiKey)
{
try
{
if(string.IsNullOrEmpty(apiKey))
throw new ArgumentNullException("api Key");
return new AnalyticsReportingService(new BaseClientService.Initializer()
{
ApiKey = apiKey,
ApplicationName = "AnalyticsReporting API key example",
});
}
catch(Exception ex)
{
throw new Exception("Failed to create new AnalyticsReporting Service", ex);
}
}
在 Test() 方法的最后一行,ars.Reports.BatchGet(getReport).Execute(); 我得到了错误:
Google.Apis.Requests.RequestError 请求缺少所需的身份验证凭据。预期的 OAuth 2 访问令牌、登录 cookie 或其他有效的身份验证凭据。
但是再次使用 OAUTH2 身份验证,我访问了用户数据,这不是我想要的。 我需要由浏览 CMS 的用户独立访问我拥有的特定帐户。
【问题讨论】:
标签: c# asp.net google-api google-analytics-api google-api-dotnet-client