C# 我想使用客户端登录在youtube上上传视频。没有打开网页的权限

C# 我想使用客户端登录在youtube上上传视频。没有打开网页的权限,c#,.net,google-api,youtube-api,google-api-dotnet-client,C#,.net,Google Api,Youtube Api,Google Api Dotnet Client,当我使用客户端登录将视频上传到YouTube时。第一次重定向到UI以获取权限 我想上传而不重定向到网页。我需要在服务器上执行此代码 这是我的密码 private async Task<string> Run(string title, string description, string filepath) { var videoID = string.Empty; try {

当我使用客户端登录将视频上传到YouTube时。第一次重定向到UI以获取权限

我想上传而不重定向到网页。我需要在服务器上执行此代码

这是我的密码

    private async Task<string> Run(string title, string description, string filepath)
        {

            var videoID = string.Empty;
            try
            {
                logger.Info(string.Format("[uploading file on youTube Title: {0}, Description: {1}, filePath: {2}]", title, description, filepath));
                UserCredential credential;
                using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
                {
                    logger.Info("[Load credentials from google start]");
                    credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        // This OAuth 2.0 access scope allows an application to upload files to the
                        // authenticated user's YouTube channel, but doesn't allow other types of access.
                        new[] { YouTubeService.Scope.YoutubeUpload },
                        "user",
                        CancellationToken.None
                    );
                    logger.Info("[Load credentials from google end]");

                }
                logger.Info("YouTubeApiKey {0}", System.Configuration.ConfigurationManager.AppSettings["YoutubeApiKey"]);
                var youtubeService = new YouTubeService(new BaseClientService.Initializer()
                  {
                      HttpClientInitializer = credential,
                      ApiKey = System.Configuration.ConfigurationManager.AppSettings["YoutubeApiKey"],
                      ApplicationName = System.Configuration.ConfigurationManager.AppSettings["ApplicationName"]
                  });

                logger.Info("ApplicationName {0}", System.Configuration.ConfigurationManager.AppSettings["ApplicationName"]);


                var video = new Video();
                video.Snippet = new VideoSnippet();
                video.Snippet.Title = title;
                video.Snippet.Description = description;
                //video.Snippet.Tags = new string[] { "tag1", "tag2" };
                // video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
                video.Status = new VideoStatus();
                video.Status.PrivacyStatus = "public"; // or "private" or "public"
                var filePath = filepath; // Replace with path to actual movie file.


                 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();

            }
                return videoID;
            }
            catch (Exception e)
            {
                logger.ErrorException("[Error occurred in Run ]", e);
            }
            return videoID;
  }

        void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
        {
            switch (progress.Status)
            {
                case UploadStatus.Uploading:
                    Console.WriteLine("{0} bytes sent.", progress.BytesSent);
                    break;

                case UploadStatus.Failed:
                    Console.WriteLine("An error prevented the upload from completing.\n{0}", progress.Exception);
                    break;
            }
        }

        void videosInsertRequest_ResponseReceived(Video video)
        {
            Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);
        }
专用异步任务运行(字符串标题、字符串描述、字符串文件路径)
{
var videoID=string.Empty;
尝试
{
Info(string.Format(“[上传youTube上的文件标题:{0},说明:{1},文件路径:{2}]”,标题,说明,文件路径));
用户凭证;
使用(var stream=newfilestream(“client_secret.json”、FileMode.Open、FileAccess.Read))
{
logger.Info(“[从google开始加载凭据]”);
凭证=等待GoogleWebAuthorizationBroker.AuthorizationAsync(
GoogleClientSecrets.Load(stream.Secrets),
//此OAuth 2.0访问范围允许应用程序将文件上载到
//已验证用户的YouTube频道,但不允许其他类型的访问。
新[]{YouTubeService.Scope.YoutubeUpload},
“用户”,
取消令牌。无
);
logger.Info(“[从google端加载凭据]”);
}
logger.Info(“YouTubeApiKey{0}”,System.Configuration.ConfigurationManager.AppSettings[“YouTubeApiKey”);
var youtubeService=new youtubeService(new BaseClientService.Initializer()
{
HttpClientInitializer=凭证,
ApiKey=System.Configuration.ConfigurationManager.AppSettings[“YouTubeAppKey”],
ApplicationName=System.Configuration.ConfigurationManager.AppSettings[“ApplicationName”]
});
logger.Info(“ApplicationName{0}”,System.Configuration.ConfigurationManager.AppSettings[“ApplicationName”]);
var video=新视频();
video.Snippet=新的VideoSnippet();
video.Snippet.Title=标题;
video.Snippet.Description=说明;
//video.Snippet.Tags=新字符串[]{“tag1”、“tag2”};
//video.Snippet.CategoryId=“22”//请参阅https://developers.google.com/youtube/v3/docs/videoCategories/list
video.Status=新的VideoStatus();
video.Status.PrivacyStatus=“public”;//或“private”或“public”
var filePath=filePath;//替换为实际电影文件的路径。
使用(var fileStream=newfilestream(filePath,FileMode.Open))
{
var videosInsertRequest=youtubeService.Videos.Insert(视频,“片段,状态”,文件流,“视频/*”;
videosInsertRequest.ProgressChanged+=videosInsertRequest\u ProgressChanged;
videosInsertRequest.ResponseReceived+=videosInsertRequest_ResponseReceived;
等待videosInsertRequest.UploadAsync();
}
返回videoID;
}
捕获(例外e)
{
logger.ErrorException(“[运行中发生错误]”,e);
}
返回videoID;
}
void videosInsertRequest_进度已更改(Google.api.Upload.IUploadProgress进度)
{
开关(进度状态)
{
案例上传状态。上传:
WriteLine(“{0}字节已发送。”,progress.BytesSent);
打破
案例上载状态。失败:
WriteLine(“一个错误阻止上载完成。\n{0}”,progress.Exception);
打破
}
}
接收到无效视频请求/响应(视频)
{
WriteLine(“视频id{0}已成功上载。”,Video.id);
}

您的代码所做的一切都是正确的。YouTube API不允许纯服务器身份验证(服务帐户)。上载文件的唯一选项是使用Oauth2并在第一次对代码进行身份验证

我只是建议你做一个小小的改变,添加文件数据存储。这将为您存储身份验证。一旦您通过web浏览器对其进行了身份验证,就不需要再次进行身份验证

/// <summary>
        /// Authenticate to Google Using Oauth2
        /// Documentation https://developers.google.com/accounts/docs/OAuth2
        /// </summary>
        /// <param name="clientId">From Google Developer console https://console.developers.google.com</param>
        /// <param name="clientSecret">From Google Developer console https://console.developers.google.com</param>
        /// <param name="userName">A string used to identify a user.</param>
        /// <returns></returns>
        public static YouTubeService AuthenticateOauth(string clientId, string clientSecret, string userName)
        {

            string[] scopes = new string[] { YouTubeService.Scope.Youtube,  // view and manage your YouTube account
                                             YouTubeService.Scope.YoutubeForceSsl,
                                             YouTubeService.Scope.Youtubepartner,
                                             YouTubeService.Scope.YoutubepartnerChannelAudit,
                                             YouTubeService.Scope.YoutubeReadonly,
                                             YouTubeService.Scope.YoutubeUpload}; 

            try
            {
                // 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
                                                                                             , userName
                                                                                             , CancellationToken.None
                                                                                             , new FileDataStore("Daimto.YouTube.Auth.Store")).Result;

                YouTubeService service = new YouTubeService(new YouTubeService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "YouTube Data API Sample",
                });
                return service;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.InnerException);
                return null;

            }
         }
您的代码需要在第一次进行身份验证。一旦通过身份验证,filedatastore就会在您的计算机上的%appData%中存储一个文件。每次运行之后,它都将使用存储在%appData%中的刷新令牌再次获得访问权限


从您的代码中提取的代码正在正确执行所有操作。YouTube API不允许纯服务器身份验证(服务帐户)。上载文件的唯一选项是使用Oauth2并在第一次对代码进行身份验证

我只是建议你做一个小小的改变,添加文件数据存储。这将为您存储身份验证。一旦您通过web浏览器对其进行了身份验证,就不需要再次进行身份验证

/// <summary>
        /// Authenticate to Google Using Oauth2
        /// Documentation https://developers.google.com/accounts/docs/OAuth2
        /// </summary>
        /// <param name="clientId">From Google Developer console https://console.developers.google.com</param>
        /// <param name="clientSecret">From Google Developer console https://console.developers.google.com</param>
        /// <param name="userName">A string used to identify a user.</param>
        /// <returns></returns>
        public static YouTubeService AuthenticateOauth(string clientId, string clientSecret, string userName)
        {

            string[] scopes = new string[] { YouTubeService.Scope.Youtube,  // view and manage your YouTube account
                                             YouTubeService.Scope.YoutubeForceSsl,
                                             YouTubeService.Scope.Youtubepartner,
                                             YouTubeService.Scope.YoutubepartnerChannelAudit,
                                             YouTubeService.Scope.YoutubeReadonly,
                                             YouTubeService.Scope.YoutubeUpload}; 

            try
            {
                // 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
                                                                                             , userName
                                                                                             , CancellationToken.None
                                                                                             , new FileDataStore("Daimto.YouTube.Auth.Store")).Result;

                YouTubeService service = new YouTubeService(new YouTubeService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "YouTube Data API Sample",
                });
                return service;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.InnerException);
                return null;

            }
         }
您的代码需要在第一次进行身份验证。一旦通过身份验证,filedatastore就会在您的计算机上的%appData%中存储一个文件。每次运行之后,它都将使用存储在%appData%中的刷新令牌再次获得访问权限


从您的报告中撕下代码。但当我运行这段代码时,这也会重定向到Web上的登录页面,应该第一次就这样做。检查%appData%,确保文件已保存。通过网页验证后,查找“Daimto.YouTube.Auth.Store”。再运行一次。它不需要您再次对其进行身份验证。是的,文件保存在该服务器上,如果我在服务器上运行此服务,则需要将该文件保存在se上