【问题标题】:Google Analytics API and .Net谷歌分析 API 和 .Net
【发布时间】:2016-04-09 04:12:59
【问题描述】:

Google 几天前宣布了Analytics Data Export API,从而使获取网站的分析数据变得更加容易。 API 与 Java 和 Javascript 客户端一起首次亮相,但没有直接的 .Net 支持(除了直接支持 XML)。不过,该 API 似乎与其他 Google 数据 API 相似,并且有一个 .Net client for those。有没有人尝试使用该库中的组件来获取分析数据?

我正在构建一个 ASP.Net MVC 网站,并认为我会使用 Google Analytics 来生成“浏览次数最多”列表和类似的东西(因为 Google 可能更擅长清除虚假请求、机器人、 ETC。)。如果您对这个想法有任何想法,我也很感激听到他们的意见。

【问题讨论】:

  • 我已经开始写一篇了。它最终将成为一个 Linq-to-Google Analytics,但我已经收藏了那个。现在它将是一个简单的包装器,应该再过一两天,我会发布一个早期版本

标签: .net asp.net-mvc api google-analytics analytics


【解决方案1】:
【解决方案2】:

在此处查看我的发布位置: http://www.akamarketing.com/blog/103-introducing-google-analytics-api-with-aspnet-c.html

它没有使用您提到的内置库,但运行良好。整个 API 是 XML/HTTP,因此使用起来非常方便。你基本上是向谷歌索要一个网页,然后检查你所需要的响应。

【讨论】:

    【解决方案3】:
     //For this you will have to add some dll in your .net project i.e.
     using DotNetOpenAuth.OAuth2;
     using Google.Apis.Authentication.OAuth2;
     using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
     using Google.Apis.Analytics.v3;
     using Google.Apis.Analytics.v3.Data;
     using Google.Apis.Services;
    
     public ActionResult GetAnalyticsData(string GroupType, string date_from, string date_to)
        {
            try
            {
    
                AnalyticsService gas = AuthenticateUser();
    
                // Creating our query
                DataResource.GaResource.GetRequest r = gas.Data.Ga.Get("ga:88028792", date_from, date_to, "ga:visits, ga:pageviews, ga:users, ga:newUsers, ga:sessions");
                //Hour,Day,Week,Month
                if (GroupType == "Hour") { r.Dimensions = "ga:nthHour"; }
                else if (GroupType == "Day") { r.Dimensions = "ga:nthDay"; }
                else if (GroupType == "Week") { r.Dimensions = "ga:nthWeek"; }
                else if (GroupType == "Month") { r.Dimensions = "ga:nthMonth"; }
    
    
                //d: Execute and fetch the results of our query
                GaData d = r.Execute();
    
                List<TotalsForAllResults> tr = new List<TotalsForAllResults>();
                List<CustomeData> cd = new List<CustomeData>();
    
                foreach (var item in d.Rows)
                {
                    CustomeData mydata = new CustomeData();
                   // mydata.CreatedDate = item[0].ToString();
                    mydata.visits = Convert.ToInt32(item[1]);
                    mydata.pageviews = Convert.ToInt32(item[2]);
                    mydata.users = Convert.ToInt32(item[3]);
                    mydata.newUsers = Convert.ToInt32(item[4]);
                    mydata.sessions = Convert.ToInt32(item[5]);
    
    
                    #region Date Conversion
    
                    DateTime Now = DateTime.Parse(date_from, CultureInfo.InvariantCulture, DateTimeStyles.None);
                    DateTime TempDate = new DateTime(Now.Year, Now.Month, Convert.ToInt32(Now.ToString("dd")));
    
                    if (GroupType == "Day")
                    {    
                        TempDate = TempDate.AddDays((Convert.ToInt32(item[0])));  
                        mydata.CreatedDate = TempDate.ToLongDateString();
                    }
                    else if (GroupType == "Hour")
                    {
                        TempDate = TempDate.AddHours((Convert.ToInt32(item[0])));
                        mydata.CreatedDate = TempDate.ToString("dddd, MMM dd, yyyy hh:mm tt"); 
                    }
                    else if (GroupType == "Month")
                    {                        
                        TempDate = TempDate.AddMonths((Convert.ToInt32(item[0])));
                        mydata.CreatedDate = TempDate.ToString("MMMM, yyyy");
                    }
                    else
                    {
                        //DateTime NewDate = DateTime.Parse(date_from, CultureInfo.InvariantCulture, DateTimeStyles.None);
                        //NewDate = NewDate.AddDays(((Convert.ToInt32(item[0]) + 1) - 1) * 7);
                        //string NewDate1 = NewDate.ToLongDateString();
                        mydata.CreatedDate = item[0].ToString();
                    }
    
                    #endregion
    
                    cd.Add(mydata);
                }
    
                foreach (var item in d.TotalsForAllResults)
                {
                    TotalsForAllResults tfa = new TotalsForAllResults();
                    tfa.metrics = item.Key;
                    tfa.count = Convert.ToInt32(item.Value);
                    tr.Add(tfa);
                }
    
                // At this point, d should contain the number of visitors you got between dates
                return Json(new { TotalsForAllResults = tr, LineChartData = cd });
            }
            catch (Exception ex)
            {
                return Json(null);
            }
    
    
    
        }
    
     public AnalyticsService AuthenticateUser()
        {
            // This is the physical path to the key file you downloaded when you created your Service Account
            String key_file = @"E:\be8eab1c9893eac9f9fdac95cd64bcc58c86a158-privatekey.p12";//@"C:\Users\path\XXXXX-privatekey.p12";
    
            // Is the "Email Address", not the "Client ID" one!!!
            String client_id = "450122396803-jt0vt4do8ui6ah74iv1idh1pt9jsvqa6@developer.gserviceaccount.com"; //"0000000-xxxxx@developer.gserviceaccount.com";
    
            // Probably the password for all is "notasecret"
            String key_pass = "notasecret";
    
            String scope_url = "https://www.googleapis.com/auth/" + Google.Apis.Analytics.v3.AnalyticsService.Scopes.Analytics.ToString().ToLower();
            //scope_url = "https://www.googleapis.com/auth/analytics";
            //scope_url = "https://www.googleapis.com/auth/analytics.readonly";
    
            AuthorizationServerDescription desc = GoogleAuthenticationServer.Description;
            X509Certificate2 key = new X509Certificate2(key_file, key_pass, X509KeyStorageFlags.Exportable);
    
            AssertionFlowClient client = new AssertionFlowClient(desc, key) { ServiceAccountId = client_id, Scope = scope_url };
            OAuth2Authenticator<AssertionFlowClient> auth = new OAuth2Authenticator<AssertionFlowClient>(client, AssertionFlowClient.GetState);
            //AnalyticsService gas = new AnalyticsService(auth);
            AnalyticsService gas = new AnalyticsService(new BaseClientService.Initializer() { Authenticator = auth });
    
            return gas;
        }
    
     using System;
     using System.Collections.Generic;
     using System.Linq;
     using System.Web;
    
    namespace GAExampleMVC.Models
    {
    public class TotalsForAllResults
    {
        public string metrics { get; set; }
        public int count { get; set; }
        public double Percent { get; set; }
        public DateTime Time { get; set; }
    
    }
    
    public class CustomeData
    {
        public string CreatedDate { get; set; }
        public int visits { get; set; }
        public int pageviews { get; set; }
        public int users { get; set; }
        public int newUsers { get; set; }
        public int sessions { get; set; }
        public string avgSessionDuration { get; set; }
        public double bounceRate { get; set; }
        public double percentNewSessions { get; set; }
        public double percentNewVisits { get; set; }
        public string Location { get; set; }
        public int uniquePageviews { get; set; }
        public string pagePath { get; set; }
    
    
    }
    

    }

    【讨论】:

      【解决方案4】:

      Google 发布了一个新品种的 API,列在 Google Api Explorer,您可以看到 Google Analytics 的条目。还有一个.Net client 为所有这些 API 提供 .dll。这是谷歌,所以它仍处于测试阶段,但我正在开发它,没有任何问题。

      【讨论】:

      • 我收到“您无权执行此方法。”当我使用询问的参数运行 data.ga.get 方法时。如果您遇到同样的问题,能否告诉我?
      猜你喜欢
      • 1970-01-01
      • 2013-03-09
      • 1970-01-01
      • 2015-09-09
      • 2016-11-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-05
      • 1970-01-01
      相关资源
      最近更新 更多