YouTube API V3 上传视频引发异常 [英] YouTube API V3 Upload video throws exception

查看:32
本文介绍了YouTube API V3 上传视频引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 C# 处理 Web 应用程序,用户将在其中浏览视频文件,Web 应用程序将通过 YouTube API V3 上传到 YouTube.我收到错误.请指教我哪里做错了?

错误:System.ArgumentNullException:值不能为空.参数名称: baseUri at Microsoft.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at Microsoft.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccess(Task task) at Microsoft.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task) at Microsoft.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult() at Google.Apis.Upload.ResumableUpload1.d__e.MoveNext() in c:\code\google.com\google-api-dotnet-client\default\Tools\Google.Apis.Release\bin\Debug\output\default\Src\GoogleApis\Apis[Media]\Upload\ResumableUpload.cs:line 459

我遵循了以下几点.

  1. 为 Web 应用程序创建 ClientID 并从 API 访问页面下载 client_secrets.json 文件.
  2. 使用了 https://developers 中提供的 .Net 示例代码.google.com/youtube/v3/docs/videos/insert#examples 还引用了来自 https://developers.google.com/youtube/v3/code_samples/dotnet
  3. 我的应用已获得 YouTube API 的授权.
  4. 上传视频文件时,出现以下错误.

我贴在我的代码下面供您参考.

/* TestFileUploader.aspx */

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestFileUploader.aspx.cs" Inherits="TestFileUploader" Async="true" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><头><身体><form id="qaform" runat="server"><div><p><asp:FileUpload runat="server" ID="FileUpload1" onchange="AddEventChoosePicture(this,'FileUpload1')"样式="宽度:100%;"/></p><p><asp:Button ID="submit" runat="server" OnClick="submit_Click" Text="Submit"/></p>

</表单></html>

/* TestFileUploader.aspx.cs */

使用系统;使用 System.Web;使用 System.IO;使用 QA.credential;使用 Google.Apis.Auth.OAuth2;使用 Google.Apis.YouTube.v3;使用 Google.Apis.Services;使用 Google.Apis.YouTube.v3.Data;使用 Google.Apis.Upload;公共部分类 TestFileUploader : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e){}protected void submit_Click(object sender, EventArgs e){尝试{如果 (FileUpload1.HasFile){String FileUpload1_Ext = System.IO.Path.GetExtension(this.FileUpload1.PostedFile.FileName);UploadVideos(FileUpload1.FileContent, FileUpload1.PostedFile.ContentType);}}捕获(异常前){Response.Write(ex.Message);}}私有异步无效 UploadVideos(Stream UploadedStream, String contenttype){尝试{UserCredential 凭证;String clientsecretkeypath = HttpContext.Current.Server.MapPath("~/client_secrets.json");使用 (var stream = new FileStream(clientsecretkeypath, FileMode.Open, FileAccess.Read)){凭据 = 等待 GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,new[] { YouTubeService.Scope.YoutubeUpload },"用户", System.Threading.CancellationToken.None);}//创建服务.var youtubeService = new YouTubeService(new BaseClientService.Initializer(){//ApiKey = "AIzaSyAFxuAA4r4pf6VX75zEwCrIh5z4QkzOZ6M",HttpClientInitializer = 凭证,ApplicationName = PhotoandVideoupload.applicationname});var video = new Video();video.Snippet = new VideoSnippet();video.Snippet.Title = "我的测试电影";video.Snippet.Description = "我的描述";video.Snippet.Tags = new string[] { "Autos" };video.Snippet.CategoryId = "2";video.Status = new VideoStatus();video.Status.PrivacyStatus = "不公开";//使用代码段,下面的状态会抛出 401(未授权问题).//单独使用代码段会抛出 404(错误请求).//在这两种情况下,参数 baseURI 都会抛出 Null 异常.var videoInsertRequest = youtubeService.Videos.Insert(video, "snippet", uploadStream, contenttype);videoInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;videoInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;Google.Apis.Upload.IUploadProgress progress = await videosInsertRequest.UploadAsync();开关(进度.状态){案例 UploadStatus.Uploading:Response.Write(String.Format("{0} 字节发送.", progress.BytesSent));休息;案例 UploadStatus.Failed:Response.Write(String.Format("{0}
", progress.Exception.Message));Response.Write(String.Format("{0}
", progress.Exception.StackTrace));休息;}//还尝试从服务器路径读取文件,而不是通过文件上传控件上传./*使用 (var fileStream = new FileStream(HttpContext.Current.Server.MapPath("~/1.mp4"), FileMode.Open)){var videoInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, contenttype);videoInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;videoInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;等待视频插入请求.上传异步();}*/}捕获(异常前){Response.Write(ex.Message + " " + ex.StackTrace);}最后{}}void videoInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress 进度){开关(进度.状态){案例 UploadStatus.Uploading:Response.Write(String.Format("{0} 字节发送.", progress.BytesSent));休息;案例 UploadStatus.Failed:Response.Write(String.Format("{0}
", progress.Exception.Message));Response.Write(String.Format("{0}
", progress.Exception.StackTrace));休息;}}void videosInsertRequest_ResponseReceived(视频视频){Response.Write(String.Format("视频 ID '{0}' 已成功上传.", video.Id));}}

请指教我哪里做错了?

谢谢,

解决方案

您可以尝试以下更改:

来自:

var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet", uploadStream, contenttype);

致:

var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", uploadStream, contenttype);

另外,内容类型是什么?我使用 video/* 作为视频上传的内容类型.

状态码 401 错误可能是因为 YouTube API 尚未获得授权.检查您是否已为您的凭据授权 YouTube API.转到 Google Developers Console 并点击您的项目名称.然后单击左侧导航菜单中的API".检查 YouTube Data API v3 是否已开启.

I am working with Web application with C# where user will browse a video file and web application will upload to YouTube via YouTube API V3. I am getting the error. Please advice where i am doing wrong?

Error: System.ArgumentNullException: Value cannot be null. Parameter name: baseUri at Microsoft.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at Microsoft.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccess(Task task) at Microsoft.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task) at Microsoft.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult() at Google.Apis.Upload.ResumableUpload1.d__e.MoveNext() in c:\code\google.com\google-api-dotnet-client\default\Tools\Google.Apis.Release\bin\Debug\output\default\Src\GoogleApis\Apis[Media]\Upload\ResumableUpload.cs:line 459

I followed the below points.

  1. Created ClientID for Webapplication and downloaded client_secrets.json file from API Access page.
  2. Used the .Net sample code provided in https://developers.google.com/youtube/v3/docs/videos/insert#examples also referred same code from https://developers.google.com/youtube/v3/code_samples/dotnet
  3. My application got authorized to YouTube API.
  4. While uploading the video file, i am getting below error.

I am pasting below my code for your reference.

/* TestFileUploader.aspx */

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestFileUploader.aspx.cs" Inherits="TestFileUploader" Async="true" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
    <form id="qaform" runat="server">
        <div>
            <p>
                <asp:FileUpload runat="server" ID="FileUpload1" onchange="AddEventChoosePicture(this,'FileUpload1')"
                    Style="width: 100%;" />
            </p>
            <p>
                <asp:Button ID="submit" runat="server" OnClick="submit_Click" Text="Submit" />
            </p>
        </div>
    </form>
</body>
</html>

/* TestFileUploader.aspx.cs */

using System;
using System.Web;
using System.IO;
using QA.credential;

using Google.Apis.Auth.OAuth2;
using Google.Apis.YouTube.v3;
using Google.Apis.Services;
using Google.Apis.YouTube.v3.Data;
using Google.Apis.Upload;

public partial class TestFileUploader : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void submit_Click(object sender, EventArgs e)
    {
        try
        {
            if (FileUpload1.HasFile)
            {
                String FileUpload1_Ext = System.IO.Path.GetExtension(this.FileUpload1.PostedFile.FileName);
                UploadVideos(FileUpload1.FileContent, FileUpload1.PostedFile.ContentType);
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }

    }

    private async void UploadVideos(Stream uploadedStream, String contenttype)
    {
        try
        {
            UserCredential credential;
            String clientsecretkeypath = HttpContext.Current.Server.MapPath("~/client_secrets.json");
            using (var stream = new FileStream(clientsecretkeypath, FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new[] { YouTubeService.Scope.YoutubeUpload },
                    "user", System.Threading.CancellationToken.None);
            }

            // Create the service.
            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                //ApiKey = "AIzaSyAFxuAA4r4pf6VX75zEwCrIh5z4QkzOZ6M",
                HttpClientInitializer = credential,
                ApplicationName = PhotoandVideoupload.applicationname
            });

            var video = new Video();
            video.Snippet = new VideoSnippet();
            video.Snippet.Title = "My Test Movie";
            video.Snippet.Description = "My description";
            video.Snippet.Tags = new string[] { "Autos" };
            video.Snippet.CategoryId = "2";
            video.Status = new VideoStatus();
            video.Status.PrivacyStatus = "unlisted";

            // Using snippet,status below throws 401(UnAuthorized issue).
            // Using snippet alone throws 404(Bad Request).
            //In both case, Null Exception throws for parameter baseURI.
            var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet", uploadedStream, contenttype);
            videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
            videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;

            Google.Apis.Upload.IUploadProgress progress = await videosInsertRequest.UploadAsync();

            switch (progress.Status)
            {
                case UploadStatus.Uploading:
                    Response.Write(String.Format("{0} bytes sent.", progress.BytesSent));
                    break;

                case UploadStatus.Failed:
                    Response.Write(String.Format("{0}<br/>", progress.Exception.Message));
                    Response.Write(String.Format("{0}<br/>", progress.Exception.StackTrace));
                    break;
            }


            // Also tried to read file from server path instead of uploading via fileupload control.
            /*
            using (var fileStream = new FileStream(HttpContext.Current.Server.MapPath("~/1.mp4"), FileMode.Open))
            {
                var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, contenttype);
                videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
                videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;

                await videosInsertRequest.UploadAsync();
            }
            */

        }
        catch (Exception ex)
        {
            Response.Write(ex.Message + " " + ex.StackTrace);
        }
        finally
        {
        }
    }

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

            case UploadStatus.Failed:
                Response.Write(String.Format("{0}<br/>", progress.Exception.Message));
                Response.Write(String.Format("{0}<br/>", progress.Exception.StackTrace));
                break;
        }
    }

    void videosInsertRequest_ResponseReceived(Video video)
    {
        Response.Write(String.Format("Video id '{0}' was successfully uploaded.", video.Id));
    }

}

Please advice where i am doing wrong?

Thanks,

解决方案

You might try the following change:

From:

var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet", uploadedStream, contenttype);

To:

var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", uploadedStream, contenttype);

Also, what is in contenttype? I use video/* as the contenttype for video uploads.

The status code 401 error may be because the YouTube API has not been authorized. Check that you have authorized the YouTube API for your credentials. Go to Google Developers Console and click on your project name. Then click on "APIs" in the left navigation menu. Check to see that YouTube Data API v3 is On.

这篇关于YouTube API V3 上传视频引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆