【发布时间】:2017-05-08 14:46:43
【问题描述】:
我正在调试一个使用 Oauth2 凭据的控制台应用程序,并且服务提供商要求我指定一个重定向 URI。我在服务提供商的 Web 门户中指定重定向 URI。该服务是谷歌分析。
我已使用 Node.js 应用程序成功测试了该服务。在服务的配置中,我指定了http://localhost:8080 的重定向URI。 Node 应用程序实际上默认在 8080 端口启动,所以我可以简单地运行 http-server,浏览到 http://localhost:8080,调用服务,然后查看带有数据的响应。
但是,当我尝试使用 C# 控制台应用程序调用相同的服务时,我在浏览器中收到 HTTP 400 错误。错误状态:
The redirect URI in the request, http://localhost:59291/authorize/, does not match the ones authorized for the OAuth client.
每次我尝试运行应用程序时,端口都会发生变化。下面是代码(引用自Analytics Reporting API V4 Client Library for .NET):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Google.Apis.AnalyticsReporting.v4;
using Google.Apis.AnalyticsReporting.v4.Data;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System.Threading;
namespace Google_Analytics_API_Test
{
class Program
{
static void Main(string[] args)
{
try
{
var credential = GetCredential().Result;
using (var svc = new AnalyticsReportingService(
new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = "Google Analytics API Console"
}))
{
var dateRange = new DateRange
{
StartDate = "2017-04-24",
EndDate = "today"
};
var sessions = new Metric
{
Expression = "ga:sessions",
Alias = "Sessions"
};
var date = new Dimension { Name = "ga:date" };
var reportRequest = new ReportRequest
{
DateRanges = new List<DateRange> { dateRange },
Dimensions = new List<Dimension> { date },
Metrics = new List<Metric> { sessions },
ViewId = "<<viewID>>"
};
var getReportsRequest = new GetReportsRequest
{
ReportRequests = new List<ReportRequest> { reportRequest }
};
var batchRequest = svc.Reports.BatchGet(getReportsRequest);
var response = batchRequest.Execute();
foreach (var x in response.Reports.First().Data.Rows)
{
Console.WriteLine(string.Join(",", x.Dimensions) +
" " + string.Join(", ", x.Metrics.First().Values));
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
static async Task<UserCredential> GetCredential()
{
using (var stream = new FileStream("client_secret.json",
FileMode.Open, FileAccess.Read))
{
const string loginEmailAddress = "<<emailAddress>>";
return await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { AnalyticsReportingService.Scope.Analytics },
loginEmailAddress, CancellationToken.None,
new FileDataStore("GoogleAnalyticsApiConsole"));
}
}
}
}
我已经搜索了一种使用静态端口配置 IIS Express 以进行调试的方法,但我不确定这里是否涉及 IIS - 而不仅仅是由 Google Analytics 库实现的 TcpClient / TcpListener 对象之类的东西?
有没有办法在 C# .NET 控制台应用程序中为异步/等待请求指定端口?
【问题讨论】:
-
您是否遵循了所有的配置步骤,包括生成和设置json文件? OAuth 回调适用于网站应用程序,而不是回调。这是 OAuth 提供者告诉您的“网站”
I just authenticated a user with this token, let him pass的方式。显然这对于桌面客户端应用程序来说毫无意义。 -
您链接到的答案显然有效,没有导致回调。创建一个新项目并按照该答案中描述的步骤操作,确保完成所有配置步骤,将所有常量设置为正确的值,将正确的设置写入 json 文件等
标签: c# .net visual-studio async-await google-api-dotnet-client