使用Google Analytics API在C#中显示信息

我一直在寻找一个好的解决scheme整天,但谷歌进化如此之快,我找不到工作。 我想要做的是,我有一个Web应用程序,其中有一个用户需要login才能看到信息的pipe理部分。 在本节中,我想要显示来自GA的一些数据,例如某些特定url的综合浏览量。 由于它不是我显示的用户信息,但谷歌分析用户我想连接传递信息(用户名/密码或APIKey),但我不知道如何。 我发现的所有样本都使用OAuth2(女巫,如果我明白,会要求访问者使用谷歌login)。

我到目前为止发现的:

  • Google的官方客户端库.Net: http : //code.google.com/p/google-api-dotnet-client/ ,没有GA的示例
  • 官方开发者帮助: https : //developers.google.com/analytics/
  • 在SO: Google AnalyticsAPI上的代码的其他问题- 以编程方式在服务器端获取页面视图,但是当我尝试进行身份validation时,我得到一个403
  • 一些访问API的源代码: http : //www.reimers.dk/jacob-reimers-blog/added-google-analytics-reader-for-net下载源代码,但我不明白它是如何工作的
  • SO上的其他问题: 使用C#进行Google Analytics访问,但没有帮助
  • 而写这个,他们build议我这09年旧的谷歌分析API和.Net …

也许我只是累了,明天就很容易find解决scheme,但现在我需要帮助!

谢谢

我做了很多search,最后从多个地方查找代码,然后围绕它自己的界面,我想出了以下解决scheme。 不知道人们在这里粘贴他们的整个代码,但我想为什么不保存其他人的时间:)

先决条件,您将需要安装Google.GData.Client和google.gdata.analytics包/ DLL。

这是做这项工作的主要人员。

namespace Utilities.Google { public class Analytics { private readonly String ClientUserName; private readonly String ClientPassword; private readonly String TableID; private AnalyticsService analyticsService; public Analytics(string user, string password, string table) { this.ClientUserName = user; this.ClientPassword = password; this.TableID = table; // Configure GA API. analyticsService = new AnalyticsService("gaExportAPI_acctSample_v2.0"); // Client Login Authorization. analyticsService.setUserCredentials(ClientUserName, ClientPassword); } /// <summary> /// Get the page views for a particular page path /// </summary> /// <param name="pagePath"></param> /// <param name="startDate"></param> /// <param name="endDate"></param> /// <param name="isPathAbsolute">make this false if the pagePath is a regular expression</param> /// <returns></returns> public int GetPageViewsForPagePath(string pagePath, DateTime startDate, DateTime endDate, bool isPathAbsolute = true) { int output = 0; // GA Data Feed query uri. String baseUrl = "https://www.google.com/analytics/feeds/data"; DataQuery query = new DataQuery(baseUrl); query.Ids = TableID; //query.Dimensions = "ga:source,ga:medium"; query.Metrics = "ga:pageviews"; //query.Segment = "gaid::-11"; var filterPrefix = isPathAbsolute ? "ga:pagepath==" : "ga:pagepath=~"; query.Filters = filterPrefix + pagePath; //query.Sort = "-ga:visits"; //query.NumberToRetrieve = 5; query.GAStartDate = startDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); query.GAEndDate = endDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); Uri url = query.Uri; DataFeed feed = analyticsService.Query(query); output = Int32.Parse(feed.Aggregates.Metrics[0].Value); return output; } public Dictionary<string, int> PageViewCounts(string pagePathRegEx, DateTime startDate, DateTime endDate) { // GA Data Feed query uri. String baseUrl = "https://www.google.com/analytics/feeds/data"; DataQuery query = new DataQuery(baseUrl); query.Ids = TableID; query.Dimensions = "ga:pagePath"; query.Metrics = "ga:pageviews"; //query.Segment = "gaid::-11"; var filterPrefix = "ga:pagepath=~"; query.Filters = filterPrefix + pagePathRegEx; //query.Sort = "-ga:visits"; //query.NumberToRetrieve = 5; query.GAStartDate = startDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); query.GAEndDate = endDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); Uri url = query.Uri; DataFeed feed = analyticsService.Query(query); var returnDictionary = new Dictionary<string, int>(); foreach (var entry in feed.Entries) returnDictionary.Add(((DataEntry)entry).Dimensions[0].Value, Int32.Parse(((DataEntry)entry).Metrics[0].Value)); return returnDictionary; } } } 

这是我用来包装它的接口和实现。

 namespace Utilities { public interface IPageViewCounter { int GetPageViewCount(string relativeUrl, DateTime startDate, DateTime endDate, bool isPathAbsolute = true); Dictionary<string, int> PageViewCounts(string pagePathRegEx, DateTime startDate, DateTime endDate); } public class GooglePageViewCounter : IPageViewCounter { private string GoogleUserName { get { return ConfigurationManager.AppSettings["googleUserName"]; } } private string GooglePassword { get { return ConfigurationManager.AppSettings["googlePassword"]; } } private string GoogleAnalyticsTableName { get { return ConfigurationManager.AppSettings["googleAnalyticsTableName"]; } } private Analytics analytics; public GooglePageViewCounter() { analytics = new Analytics(GoogleUserName, GooglePassword, GoogleAnalyticsTableName); } #region IPageViewCounter Members public int GetPageViewCount(string relativeUrl, DateTime startDate, DateTime endDate, bool isPathAbsolute = true) { int output = 0; try { output = analytics.GetPageViewsForPagePath(relativeUrl, startDate, endDate, isPathAbsolute); } catch (Exception ex) { Logger.Error(ex); } return output; } public Dictionary<string, int> PageViewCounts(string pagePathRegEx, DateTime startDate, DateTime endDate) { var input = analytics.PageViewCounts(pagePathRegEx, startDate, endDate); var output = new Dictionary<string, int>(); foreach (var item in input) { if (item.Key.Contains('&')) { string[] key = item.Key.Split(new char[] { '?', '&' }); string newKey = key[0] + "?" + key.FirstOrDefault(k => k.StartsWith("p=")); if (output.ContainsKey(newKey)) output[newKey] += item.Value; else output[newKey] = item.Value; } else output.Add(item.Key, item.Value); } return output; } #endregion } } 

而现在剩下的就是显而易见的东西 – 你将不得不添加web.config的值到你的应用程序configuration或webconfig并调用IPageViewCounter.GetPageViewCount

它需要在谷歌方面的一些设置,但实际上很简单。 我将一步一步列出。

首先,您需要在Google云端控制台中创build一个应用程序,并启用Analytics API。

  • 转到http://code.google.com/apis/console
  • select下拉菜单并创build一个项目,如果你还没有的话
  • 一旦创build项目,请点击服务
  • 从这里启用Analytics API

现在Analytics API已启用,下一步将启用服务帐户以访问您所需的分析configuration文件/网站。 该服务帐户将允许您login,而无需提示用户input凭据。

  • 转到http://code.google.com/apis/console并从下拉列表中select您创build的项目。;
  • 接下来转到“API访问”部分,然后单击“创build另一个客户端ID”button。
  • 在创build客户端ID窗口中select服务帐户,然后单击创build客户端ID。
  • 如果该帐户没有自动开始下载,请下载该帐户的公用密钥。稍后,当您为授权编码时,您将需要此密码。
  • 在退出复制之前,服务帐户会自动生成电子邮件地址,因为您将在下一步中使用该地址。 客户电子邮件看起来像@ developer.gserviceaccount.com

现在我们有一个服务帐户,您将需要允许此服务帐户访问Google Analytics中的个人资料/网站。

  • login到Google Analytics。
  • login后,点击屏幕右上方的pipe理button。
  • 在pipe理中点击帐户下拉菜单并select您希望您的服务帐户可以访问的帐户/站点,然后点击帐户部分下的“用户pipe理”。
  • input为您的服务帐户生成的电子邮件地址,并给它读取和分析权限。
  • 对您希望您的服务有权访问的任何其他帐户/站点重复这些步骤。

现在,设置已完成,服务帐户通过API访问Google Analytics,我们可以开始编码。

从NuGet获取这个包:

Google.Apis.Analytics.v3客户端库

添加这些使用:

 using Google.Apis.Analytics.v3; using Google.Apis.Analytics.v3.Data; using Google.Apis.Services; using System.Security.Cryptography.X509Certificates; using Google.Apis.Auth.OAuth2; using System.Collections.Generic; using System.Linq; 

有些事情要注意。

  • keyPath是通过.p12文件扩展下载的密钥文件的path。
  • accountEmailAddress是我们之前得到的api邮件。
  • 作用域是Google.Apis.Analytics.v3.AnalyticService类中的一个Enum,指示要授权使用的url(例如: AnalyticsService.Scope.AnalyticsReadonly )。
  • 应用程序名称是您select的名称,告诉谷歌API什么是访问它(又名:它可以是你所select的)。

那么做一些基本调用的代码如下。

 public class GoogleAnalyticsAPI { public AnalyticsService Service { get; set; } public GoogleAnalyticsAPI(string keyPath, string accountEmailAddress) { var certificate = new X509Certificate2(keyPath, "notasecret", X509KeyStorageFlags.Exportable); var credentials = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(accountEmailAddress) { Scopes = new[] { AnalyticsService.Scope.AnalyticsReadonly } }.FromCertificate(certificate)); Service = new AnalyticsService(new BaseClientService.Initializer() { HttpClientInitializer = credentials, ApplicationName = "WorthlessVariable" }); } public AnalyticDataPoint GetAnalyticsData(string profileId, string[] dimensions, string[] metrics, DateTime startDate, DateTime endDate) { AnalyticDataPoint data = new AnalyticDataPoint(); if (!profileId.Contains("ga:")) profileId = string.Format("ga:{0}", profileId); //Make initial call to service. //Then check if a next link exists in the response, //if so parse and call again using start index param. GaData response = null; do { int startIndex = 1; if (response != null && !string.IsNullOrEmpty(response.NextLink)) { Uri uri = new Uri(response.NextLink); var paramerters = uri.Query.Split('&'); string s = paramerters.First(i => i.Contains("start-index")).Split('=')[1]; startIndex = int.Parse(s); } var request = BuildAnalyticRequest(profileId, dimensions, metrics, startDate, endDate, startIndex); response = request.Execute(); data.ColumnHeaders = response.ColumnHeaders; data.Rows.AddRange(response.Rows); } while (!string.IsNullOrEmpty(response.NextLink)); return data; } private DataResource.GaResource.GetRequest BuildAnalyticRequest(string profileId, string[] dimensions, string[] metrics, DateTime startDate, DateTime endDate, int startIndex) { DataResource.GaResource.GetRequest request = Service.Data.Ga.Get(profileId, startDate.ToString("yyyy-MM-dd"), endDate.ToString("yyyy-MM-dd"), string.Join(",", metrics)); request.Dimensions = string.Join(",", dimensions); request.StartIndex = startIndex; return request; } public IList<Profile> GetAvailableProfiles() { var response = Service.Management.Profiles.List("~all", "~all").Execute(); return response.Items; } public class AnalyticDataPoint { public AnalyticDataPoint() { Rows = new List<IList<string>>(); } public IList<GaData.ColumnHeadersData> ColumnHeaders { get; set; } public List<IList<string>> Rows { get; set; } } } 

其他有用的链接:

分析API浏览器 – 从Web查询API

分析API Explorer版本2 – 从Web查询API

维度和指标参考

希望这可以帮助有人试图在未来做到这一点。

我希望只是为v3 Beta的答案添加评论,但是rep points阻止了这一点。 但是,我认为这对于其他人来说是非常好的,

 using Google.Apis.Authentication.OAuth2; using Google.Apis.Authentication.OAuth2.DotNetOpenAuth; using System.Security.Cryptography.X509Certificates; using Google.Apis.Services; 

这个名字空间在整篇文章的代码中使用。 我总是希望人们能更频繁地发表名字空间,我似乎花了很多时间寻找他们。 我希望这可以节省一些人几分钟的工作。

我已经在nuGet包中设置了类似于上述答案的东西。 它具有以下function: – 连接到您在API控制台中设置的“服务帐户” – 提取所需的任何Google Analytics数据 – 使用Google的Charts API显示该数据,并以非常容易修改的方式执行所有操作。 你可以在这里看到更多: https : //www.nuget.org/packages/GoogleAnalytics.GoogleCharts.NET/ 。

这个答案适用于那些想要访问您自己的Google Analytics帐户并希望使用新的Analytics Reporting API v4的人 。

我最近写了一篇关于如何使用C#获取Google Analytics数据的博文 。 阅读所有的细节。

您首先需要select使用OAuth2还是服务帐户进行连接。 我假设您拥有Google Analytics帐户,因此您需要从Google API 凭据页面创build一个“服务帐户密钥”。

一旦你创build了,下载JSON文件并把它放在你的项目(我把我的App_Data文件夹)。

接下来,安装Google.Apis.AnalyticsReporting.v4 Nuget包。 同时安装Newtonsoft的Json.NET 。

在你的项目的某个地方包括这个类:

 public class PersonalServiceAccountCred { public string type { get; set; } public string project_id { get; set; } public string private_key_id { get; set; } public string private_key { get; set; } public string client_email { get; set; } public string client_id { get; set; } public string auth_uri { get; set; } public string token_uri { get; set; } public string auth_provider_x509_cert_url { get; set; } public string client_x509_cert_url { get; set; } } 

这就是你一直在等待的:一个完整​​的例子!

 string keyFilePath = Server.MapPath("~/App_Data/Your-API-Key-Filename.json"); string json = System.IO.File.ReadAllText(keyFilePath); var cr = JsonConvert.DeserializeObject(json); var xCred = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(cr.client_email) { Scopes = new[] { AnalyticsReportingService.Scope.Analytics } }.FromPrivateKey(cr.private_key)); using (var svc = new AnalyticsReportingService( new BaseClientService.Initializer { HttpClientInitializer = xCred, ApplicationName = "[Your Application Name]" }) ) { // Create the DateRange object. DateRange dateRange = new DateRange() { StartDate = "2017-05-01", EndDate = "2017-05-31" }; // 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. ReportRequest reportRequest = new ReportRequest { ViewId = "[A ViewId in your account]", DateRanges = new List() { dateRange }, Dimensions = new List() { browser }, Metrics = new List() { sessions } }; List requests = new List(); requests.Add(reportRequest); // Create the GetReportsRequest object. GetReportsRequest getReport = new GetReportsRequest() { ReportRequests = requests }; // Call the batchGet method. GetReportsResponse response = svc.Reports.BatchGet(getReport).Execute(); } 

我们首先从JSON文件反序列化服务帐户密钥信息并将其转换为PersonalServiceAccountCred对象。 然后,我们创buildServiceAccountCredential并通过AnalyticsReportingService连接到Google。 使用这个服务,我们准备一些基本的filter传递给API并发送请求。

最好在声明responsevariables的行上设置一个断点,按F10一次,然后将鼠标hover在variables上,以便可以查看哪些数据可供您在响应中使用。

希望谷歌有一天会提供适当的文件。 在这里,我列出了将ASP.NET分析服务器端身份validation集成到ASP.NET C#中的所有步骤。

第1步:在Google控制台中创build一个项目

转到链接https://console.developers.google.com/iam-admin/projects并通过点击“创build项目”button创build一个项目,并在popup窗口中提供项目名称并提交。;

第2步:创build凭据和服务帐户

创build项目后,您将被redirect到“API Manager”页面。 点击凭据,然后按“创build凭证”button。 从下拉列表中select“服务帐号密钥”,您将被redirect到下一页。 在服务帐户下拉菜单中,select“新build服务帐户”。 填写服务帐户名称并下载p12密钥。 它将有p12扩展名。 你会得到一个popup的密码“ notasecret ”,这是默认的,你的私钥将被下载。

第3步:创build0auth客户端ID

点击“创build凭证”下拉菜单并select“0auth客户端ID”,您将被redirect到“0auth同意屏幕”选项卡。 在项目名称文本框中提供一个随机名称。 select应用程序types为“Web应用程序”,然后点击创buildbutton。 将生成的客户端ID复制到记事本中。

第4步:启用API

在左侧点击“概览”选项卡,并从水平选项卡中select“启用的API”。 在search栏中search“Analytics API”,点击下拉菜单中的“启用”button。 现在再次search“Analytics Reporting V4”并启用它。

第5步:安装nuget包

在Visual Studio中,转到工具> Nuget Package Manager>程序包pipe理器控制台。 将以下代码复制粘贴到控制台中以安装nuget软件包。

安装包Google.Apis.Analytics.v3

安装包DotNetOpenAuth.Core – 版本4.3.4.13329

以上两个包是Google Analytics和DotNetOpenAuth nuget包。

第6步:提供服务帐户的“查看和分析”权限

转到谷歌分析帐户,并点击“pipe理”选项卡,并从左侧菜单中select“用户pipe理”,select您要访问分析数据的域,并在其下面插入服务帐户的电子邮件ID,并select“读取和分析”权限从下拉菜单中select 服务帐户电子邮件ID看起来像例如: googleanalytics@googleanalytics.iam.gserviceaccount.com

工作代码

前端代码:

将以下分析embedded脚本复制并粘贴到您的前端,否则您也可以从Google分析文档页面获取此代码。

  <script> (function (w, d, s, g, js, fs) { g = w.gapi || (w.gapi = {}); g.analytics = { q: [], ready: function (f) { this.q.push(f); } }; js = d.createElement(s); fs = d.getElementsByTagName(s)[0]; js.src = 'https://apis.google.com/js/platform.js'; fs.parentNode.insertBefore(js, fs); js.onload = function () { g.load('analytics'); }; }(window, document, 'script'));</script> 

将以下代码粘贴到您的前端页面的正文标记中。

  <asp:HiddenField ID="accessToken" runat="server" /> <div id="chart-1-container" style="width:600px;border:1px solid #ccc;"></div> <script> var access_token = document.getElementById('<%= accessToken.ClientID%>').value; gapi.analytics.ready(function () { /** * Authorize the user with an access token obtained server side. */ gapi.analytics.auth.authorize({ 'serverAuth': { 'access_token': access_token } }); /** * Creates a new DataChart instance showing sessions. * It will be rendered inside an element with the id "chart-1-container". */ var dataChart1 = new gapi.analytics.googleCharts.DataChart({ query: { 'ids': 'ga:53861036', // VIEW ID <-- Goto your google analytics account and select the domain whose analytics data you want to display on your webpage. From the URL ex: a507598w53044903p53861036. Copy the digits after "p". It is your view ID 'start-date': '2016-04-01', 'end-date': '2016-04-30', 'metrics': 'ga:sessions', 'dimensions': 'ga:date' }, chart: { 'container': 'chart-1-container', 'type': 'LINE', 'options': { 'width': '100%' } } }); dataChart1.execute(); /** * Creates a new DataChart instance showing top 5 most popular demos/tools * amongst returning users only. * It will be rendered inside an element with the id "chart-3-container". */ }); </script> 

您也可以从https://ga-dev-tools.appspot.com/account-explorer/获取您的查看ID

后退代码:

  using System; using System.Linq; using System.Collections.Generic; using System.Collections.Specialized; using System.Web.Script.Serialization; using System.Net; using System.Text; using Google.Apis.Analytics.v3; using Google.Apis.Analytics.v3.Data; using Google.Apis.Services; using System.Security.Cryptography.X509Certificates; using Google.Apis.Auth.OAuth2; using Google.Apis.Util; using DotNetOpenAuth.OAuth2; using System.Security.Cryptography; namespace googleAnalytics { public partial class api : System.Web.UI.Page { public const string SCOPE_ANALYTICS_READONLY = "https://www.googleapis.com/auth/analytics.readonly"; string ServiceAccountUser = "googleanalytics@googleanalytics.iam.gserviceaccount.com"; //service account email ID string keyFile = @"D:\key.p12"; //file link to downloaded key with p12 extension protected void Page_Load(object sender, EventArgs e) { string Token = Convert.ToString(GetAccessToken(ServiceAccountUser, keyFile, SCOPE_ANALYTICS_READONLY)); accessToken.Value = Token; var certificate = new X509Certificate2(keyFile, "notasecret", X509KeyStorageFlags.Exportable); var credentials = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(ServiceAccountUser) { Scopes = new[] { AnalyticsService.Scope.AnalyticsReadonly } }.FromCertificate(certificate)); var service = new AnalyticsService(new BaseClientService.Initializer() { HttpClientInitializer = credentials, ApplicationName = "Google Analytics API" }); string profileId = "ga:53861036"; string startDate = "2016-04-01"; string endDate = "2016-04-30"; string metrics = "ga:sessions,ga:users,ga:pageviews,ga:bounceRate,ga:visits"; DataResource.GaResource.GetRequest request = service.Data.Ga.Get(profileId, startDate, endDate, metrics); GaData data = request.Execute(); List<string> ColumnName = new List<string>(); foreach (var h in data.ColumnHeaders) { ColumnName.Add(h.Name); } List<double> values = new List<double>(); foreach (var row in data.Rows) { foreach (var item in row) { values.Add(Convert.ToDouble(item)); } } values[3] = Math.Truncate(100 * values[3]) / 100; txtSession.Text = values[0].ToString(); txtUsers.Text = values[1].ToString(); txtPageViews.Text = values[2].ToString(); txtBounceRate.Text = values[3].ToString(); txtVisits.Text = values[4].ToString(); } public static dynamic GetAccessToken(string clientIdEMail, string keyFilePath, string scope) { // certificate var certificate = new X509Certificate2(keyFilePath, "notasecret"); // header var header = new { typ = "JWT", alg = "RS256" }; // claimset var times = GetExpiryAndIssueDate(); var claimset = new { iss = clientIdEMail, scope = scope, aud = "https://accounts.google.com/o/oauth2/token", iat = times[0], exp = times[1], }; JavaScriptSerializer ser = new JavaScriptSerializer(); // encoded header var headerSerialized = ser.Serialize(header); var headerBytes = Encoding.UTF8.GetBytes(headerSerialized); var headerEncoded = Convert.ToBase64String(headerBytes); // encoded claimset var claimsetSerialized = ser.Serialize(claimset); var claimsetBytes = Encoding.UTF8.GetBytes(claimsetSerialized); var claimsetEncoded = Convert.ToBase64String(claimsetBytes); // input var input = headerEncoded + "." + claimsetEncoded; var inputBytes = Encoding.UTF8.GetBytes(input); // signature var rsa = certificate.PrivateKey as RSACryptoServiceProvider; var cspParam = new CspParameters { KeyContainerName = rsa.CspKeyContainerInfo.KeyContainerName, KeyNumber = rsa.CspKeyContainerInfo.KeyNumber == KeyNumber.Exchange ? 1 : 2 }; var aescsp = new RSACryptoServiceProvider(cspParam) { PersistKeyInCsp = false }; var signatureBytes = aescsp.SignData(inputBytes, "SHA256"); var signatureEncoded = Convert.ToBase64String(signatureBytes); // jwt var jwt = headerEncoded + "." + claimsetEncoded + "." + signatureEncoded; var client = new WebClient(); client.Encoding = Encoding.UTF8; var uri = "https://accounts.google.com/o/oauth2/token"; var content = new NameValueCollection(); content["assertion"] = jwt; content["grant_type"] = "urn:ietf:params:oauth:grant-type:jwt-bearer"; string response = Encoding.UTF8.GetString(client.UploadValues(uri, "POST", content)); var result = ser.Deserialize<dynamic>(response); object pulledObject = null; string token = "access_token"; if (result.ContainsKey(token)) { pulledObject = result[token]; } //return result; return pulledObject; } private static int[] GetExpiryAndIssueDate() { var utc0 = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); var issueTime = DateTime.UtcNow; var iat = (int)issueTime.Subtract(utc0).TotalSeconds; var exp = (int)issueTime.AddMinutes(55).Subtract(utc0).TotalSeconds; return new[] { iat, exp }; } } } 

另一种工作方法

在ConfigAuth中添加以下代码

  var googleApiOptions = new GoogleOAuth2AuthenticationOptions() { AccessType = "offline", // can use only if require ClientId = ClientId, ClientSecret = ClientSecret, Provider = new GoogleOAuth2AuthenticationProvider() { OnAuthenticated = context => { context.Identity.AddClaim(new Claim("Google_AccessToken", context.AccessToken)); if (context.RefreshToken != null) { context.Identity.AddClaim(new Claim("GoogleRefreshToken", context.RefreshToken)); } context.Identity.AddClaim(new Claim("GoogleUserId", context.Id)); context.Identity.AddClaim(new Claim("GoogleTokenIssuedAt", DateTime.Now.ToBinary().ToString())); var expiresInSec = 10000; context.Identity.AddClaim(new Claim("GoogleTokenExpiresIn", expiresInSec.ToString())); return Task.FromResult(0); } }, SignInAsAuthenticationType = DefaultAuthenticationTypes.ApplicationCookie }; googleApiOptions.Scope.Add("openid"); // Need to add for google+ googleApiOptions.Scope.Add("profile");// Need to add for google+ googleApiOptions.Scope.Add("email");// Need to add for google+ googleApiOptions.Scope.Add("https://www.googleapis.com/auth/analytics.readonly"); app.UseGoogleAuthentication(googleApiOptions); 

添加下面的代码,名称空间和相对引用

  using Google.Apis.Analytics.v3; using Google.Apis.Analytics.v3.Data; using Google.Apis.Auth.OAuth2; using Google.Apis.Auth.OAuth2.Flows; using Google.Apis.Auth.OAuth2.Responses; using Google.Apis.Services; using Microsoft.AspNet.Identity; using Microsoft.Owin.Security; using System; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; public class HomeController : Controller { AnalyticsService service; public IAuthenticationManager AuthenticationManager { get { return HttpContext.GetOwinContext().Authentication; } } public async Task<ActionResult> AccountList() { service = new AnalyticsService(new BaseClientService.Initializer() { HttpClientInitializer = await GetCredentialForApiAsync(), ApplicationName = "Analytics API sample", }); //Account List ManagementResource.AccountsResource.ListRequest AccountListRequest = service.Management.Accounts.List(); //service.QuotaUser = "MyApplicationProductKey"; Accounts AccountList = AccountListRequest.Execute(); return View(); } private async Task<UserCredential> GetCredentialForApiAsync() { var initializer = new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = new ClientSecrets { ClientId = ClientId, ClientSecret = ClientSecret, }, Scopes = new[] { "https://www.googleapis.com/auth/analytics.readonly" } }; var flow = new GoogleAuthorizationCodeFlow(initializer); var identity = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ApplicationCookie); if (identity == null) { Redirect("/Account/Login"); } var userId = identity.FindFirstValue("GoogleUserId"); var token = new TokenResponse() { AccessToken = identity.FindFirstValue("Google_AccessToken"), RefreshToken = identity.FindFirstValue("GoogleRefreshToken"), Issued = DateTime.FromBinary(long.Parse(identity.FindFirstValue("GoogleTokenIssuedAt"))), ExpiresInSeconds = long.Parse(identity.FindFirstValue("GoogleTokenExpiresIn")), }; return new UserCredential(flow, userId, token); } } 

将其添加到Global.asax的Application_Start()中

  AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;