C# 从谷歌分析检索数据?403错误

C# 从谷歌分析检索数据?403错误,c#,.net,asp.net-mvc,google-analytics-api,nopcommerce,C#,.net,Asp.net Mvc,Google Analytics Api,Nopcommerce,我试图从谷歌分析API中提取一些数据。但是,当我运行应用程序时,我得到一个403错误,表示-请求执行失败: 我不确定代码或URL是否有问题 此行导致错误: return service.Query(dataQuery); 这是浏览器中的错误: return service.Query(dataQuery); 远程服务器返回错误:(403)禁止 描述:在执行过程中发生未处理的异常 当前的web请求。请查看堆栈跟踪以了解更多信息 有关错误的信息及其在代码中的来源 异常详细信息:System.Ne

我试图从谷歌分析API中提取一些数据。但是,当我运行应用程序时,我得到一个403错误,表示-请求执行失败:

我不确定代码或URL是否有问题

此行导致错误:

return service.Query(dataQuery);
这是浏览器中的错误:

return service.Query(dataQuery);
远程服务器返回错误:(403)禁止

描述:在执行过程中发生未处理的异常 当前的web请求。请查看堆栈跟踪以了解更多信息 有关错误的信息及其在代码中的来源

异常详细信息:System.Net.WebException:远程服务器返回错误:(403)禁止

分析类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Google.GData.Analytics;
using GoogleChartSharp;
using Nop.Admin.Models;

namespace Nop.Web.Models
{
    public static class Analytics
    {    
        private const int IMAGE_WIDTH = 900;
        private const int IMAGE_HEIGHT = 200;
        private const string DATAFEED_URL = "https://www.google.com/analytics/feeds/data?ids=ga:12345678&dimensions=ga:date&metrics=ga:visits&start-date=2014-02-16&end-date=2014-02-19";    
        private const string USERNAME = "mymail@gmail.com";
        private const string PASSWORD = "mypassword!";
        private const string PROFILE_ID = "ga:12345678";              

        private static DataFeed AnalyticsVisitorsThisMonth()
        {
            // Google Analytics Service. The name dosnt mather.
            var service = new AnalyticsService("WebSiteAnalytics");

            // Add your credentials
            service.setUserCredentials(USERNAME, PASSWORD);

            // The Data Query (What to fetch from google analytics)
            // Read more about it here: http://code.google.com/intl/sv-SE/apis/analytics/
            var dataQuery = new DataQuery(DATAFEED_URL)
            {
                Ids = PROFILE_ID,
                Metrics = "ga:visits",
                Sort = "ga:day",
                Dimensions = "ga:day",
                GAStartDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).ToString("yyyy-MM-dd"),
                GAEndDate = DateTime.Now.ToString("yyyy-MM-dd")
            };

            return service.Query(dataQuery);
        }


        private static int[] FixChartData(List<int> data, out int iMax)
        {
            List<int> chartData = new List<int>();

            iMax = data.Max();
            iMax = (int)(Math.Ceiling(iMax / 10.0d) * 10);

            foreach (var i in data)
            {
                chartData.Add((int)(((double)61 / (double)iMax) * i));
            }

            for (int i = chartData.Count; i < 32; i++)
            {
                chartData.Add(0);
            }
            return chartData.ToArray();
        }


        public static string VisitorsThisMonth()
        {
            // Fetch the datafeed from google analytics
            DataFeed df = AnalyticsVisitorsThisMonth();

            List<int> data = new List<int>();
            int[] chartData;
            int iMax = 1;

            // Create a list of values
            foreach (var ae in df.Entries)
            {
                data.Add(int.Parse(((DataEntry)(ae)).Metrics[0].Value));
            }

            // Fix the data (max value = 61) and add coming days of the month.
            chartData = FixChartData(data, out iMax);

            // Create the chart, here you can laborite yourself
            LineChart chart = new LineChart(IMAGE_WIDTH, IMAGE_HEIGHT, LineChartType.SingleDataSet);
            chart.SetData(chartData.ToArray());
            chart.AddFillArea(new FillArea("ACC3FF", 0));
            chart.SetDatasetColors(new string[] { "000000" });
            chart.SetLegend(new string[] { "Visitors" });

            chart.SetTitle("Visitors this month", "000000", 14);


            ChartAxis leftAxis = new ChartAxis(ChartAxisType.Left);
            leftAxis.SetRange(0, (int)(Math.Ceiling(iMax / 10.0d) * 10));
            chart.AddAxis(leftAxis);

            ChartAxis bottomAxis = new ChartAxis(ChartAxisType.Bottom);
            bottomAxis.SetRange(1, 31);
            chart.AddAxis(bottomAxis);

            return chart.GetUrl();
        }

    }
}
公司观点:

@using Telerik.Web.Mvc.UI
@using GoogleAnalyticsTracker;
@using Google;
@using GoogleAnalyticsTracker.Web.Mvc;
@{
    ViewBag.Title = "Company";
    Layout = "~/Views/Shared/_AdminLayout.cshtml";
}

<h2>Company</h2>


<img src="@Nop.Web.Models.Analytics.VisitorsThisMonth()" alt="Visitors this month" />
@使用Telerik.Web.Mvc.UI
@使用GoogleAnalyticsTracker;
@使用谷歌;
@使用GoogleAnalyticsTracker.Web.Mvc;
@{
ViewBag.Title=“公司”;
Layout=“~/Views/Shared/_AdminLayout.cshtml”;
}
单位

403表示您可能没有读取数据的权限。如果您确定使用的用户名/密码正确,请确保配置文件ID也正确

当您登录到analytics时,您的URL看起来像

确保您分配给PROFILE_ID的号码是“p”之后的号码(“在我的情况下是ga:zzzzzz”)


如果这对您没有帮助,我建议您切换到OAuth身份验证,因为您使用的旧方法已被Google弃用,并且不能保证有效

我不相信客户端登录与您需要使用的Google analytics配合使用。代码看起来像这样

UserCredential credential; 
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
          new ClientSecrets { ClientId = "YourClientId", ClientSecret = "YourClientSecret" },
          new[] { AnalyticsService.Scope.AnalyticsReadonly},
          "user",
          CancellationToken.None,
          new FileDataStore("Drive.Auth.Store")).Result; } 
一旦您进行了身份验证,您只需创建AnalyticsService,然后所有请求都将通过此服务

AnalyticsService service = new AnalyticsService(
                           new BaseClientService.Initializer() {
                           HttpClientInitializer = credential,
                           ApplicationName = "Analytics API sample", });

如果切换到OAuth身份验证,我是否可以使用相同的代码,是否只需更改url?我还注册了OAuth,并拥有相关的凭证、browserkey、serverkey等。我复制了谷歌分析URL中“p”后面的数字,但没有帮助。错误仍然存在。@Kristoferandersson不,您不能对OAuth使用相同的代码,您可以尝试DalmTo发布的代码,看起来过于简单,但可以工作。如果没有帮助,我可以从我的项目发布工作代码。谢谢。我现在正在尝试,你能帮我为本教程提供正确的引用/名称空间吗。和自动取款机打交道。我要聊一个小时左右。我可以帮你让它工作。我只完成了一部分示例项目。我是否必须将“user”更改为google accaont用户名,将ApplicationName更改为本地应用程序的名称?还是仅仅为了填上客户ID和客户机密就令人窒息?感恩节真是一件怪事。据我所知,它仅用于在您使用fileDataStore时重置登录名。如果您更改它,它将再次请求用户身份验证。好的,那么您只需用自己的凭据填写“ClientId”和“ClientSecret”。我的意思是,我是否有权更改“user”和“ApplicationName”的值?我也可以运行您的代码,但在本教程的这一部分中调试时,我得到了null——尽管我填写了ClientID和ClientSecret。