【发布时间】:2018-11-27 05:47:41
【问题描述】:
我正在使用从 Nuget 下载的 Youtube .Net 库。
我创建了一个 Windows 服务,它正在检查一个文件夹以将新视频上传到 youtube。我使用控制台应用程序进行了测试,在这种情况下,用户必须在网络浏览器上手动进行授权,之后我可以毫无问题地将视频上传到 youtube。问题是当我尝试使用离线访问时。
当我在 Windows 服务上运行我的代码时,我无法从用户那里获得手动授权,所以我按照这个答案创建了我的访问令牌:https://stackoverflow.com/a/20689423/2277059
问题是我没有找到任何使用独立版本的代码示例,所以我有点迷茫。使用我当前的代码,我在尝试上传视频时总是遇到错误:“unauthorized_client”。您可以在我的代码“client_secrets.json”中看到的 JSON 文件是您在为 YouTube API V3 创建凭据时自动生成的文件。
我也试过这个:https://stackoverflow.com/a/43895931/2277059,但得到了同样的错误。
现在我没有从代码中刷新令牌,只是在 OAuth Playground 上进行并测试服务。一旦成功,我将研究如何在每次查询时刷新令牌。
创建凭据时,我选择了“其他”类型,因为这是 Windows 服务。
是我的代码有问题还是我在配置中遗漏了什么?
这是我的代码:
var token = new TokenResponse()
{
AccessToken = "werwdsgfdg...",
ExpiresInSeconds = 3600,
RefreshToken = "3/dsdfsf...",
TokenType = "Bearer"
};
Log.Info("Generating user credentials and secrets");
UserCredential credential;
string credentialsPath = System.AppDomain.CurrentDomain.BaseDirectory + "client_secrets.json";
using (var stream = new FileStream(credentialsPath, FileMode.Open, FileAccess.Read))
{
credential = new UserCredential(new GoogleAuthorizationCodeFlow(
new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = GoogleClientSecrets.Load(stream).Secrets,
Scopes = new[] { YouTubeService.Scope.YoutubeUpload }
}
), EsSettings.YoutubeUser, token);
}
Log.Info("Generating youtube service");
//GoogleAuthorizationCodeFlow
YouTubeService youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
});
Log.Info("Uploading...");
using (var fileStream = new FileStream(filePath, FileMode.Open))
{
var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;
await videosInsertRequest.UploadAsync();
}
【问题讨论】:
标签: c# google-api google-oauth youtube-data-api google-api-dotnet-client