youtube 通过 C# 添加订阅

youtube Add Subscription via C#

我正在为 windows 8.1 构建 YouTube 应用。

我遇到了问题,添加(插入)订阅失败

我的代码:

var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                new Uri("ms-appx:///Assets/client_secrets.json"),
                new[] { Uri.EscapeUriString(YouTubeService.Scope.Youtube) },
                "user",
                CancellationToken.None);

var youtubeService = new YouTubeService(new BaseClientService.Initializer()
                {
                    ApiKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
                    HttpClientInitializer = credential,
                    ApplicationName = "AppName"
                });

Subscription body = new Subscription();
body.Snippet = new SubscriptionSnippet();

body.Snippet.ChannelId = "UC-kezFAw46x-9ctBUqVe86Q"; 
try
{
    var addSubscriptionRequest = youtubeService.Subscriptions.Insert(body, "snippet");
    var addSubscriptionResponse = await addSubscriptionRequest.ExecuteAsync();
}
catch (Exception e)
{
    throw e;
}

当我在第一行设置断点时。

当执行到最后一行时,中断这个函数

更新(2015-11-14):

错误信息: 请求中指定的订阅资源必须使用 snippet.resorceId 属性标识正在订阅的频道[400]

成功代码:

var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
         new Uri("ms-appx:///Assets/client_secrets.json"),
         new[] { Uri.EscapeUriString(YouTubeService.Scope.Youtube) },
         "user",
         CancellationToken.None);

var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
    //ApiKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    HttpClientInitializer = credential,
    ApplicationName = "4GameTV"
});


try
{
    Subscription body = new Subscription();
    body.Snippet = new SubscriptionSnippet();
    body.Snippet.ResourceId = new ResourceId();
    body.Snippet.ResourceId.ChannelId = "UC-kezFAw46x-9ctBUqVe86Q";  //replace with specified channel id

    var addSubscriptionRequest = youtubeService.Subscriptions.Insert(body, "snippet");
    var addSubscriptionResponse = await addSubscriptionRequest.ExecuteAsync();

}
catch (Exception e)
{
    throw e;
}

您的身份验证似乎与我通常使用的有点不同。此外,仅当您想访问 public 数据时才需要 ApiKey。

string[] scopes = new string[] { YouTubeService.Scope.Youtube };


 // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
, scopes
, "test"
, CancellationToken.None
, new FileDataStore("Daimto.YouTube.Auth.Store")).Result;

YouTubeService service = new YouTubeService(new YouTubeService.Initializer()
     {
     HttpClientInitializer = credential,
     ApplicationName = "YouTube Data API Sample",
     });