【问题标题】:YouTube API V3 Upload video throws exceptionYouTube API V3 上传视频抛出异常
【发布时间】:2014-11-03 23:05:02
【问题描述】:

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

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

我遵循以下几点。

  1. 为 Web 应用程序创建 ClientID 并从 API 访问页面下载 client_secrets.json 文件。
  2. 使用了https://developers.google.com/youtube/v3/docs/videos/insert#examples 中提供的.Net 示例代码,也引用了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">
<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));
    }

}

请指教我哪里做错了?

谢谢,

【问题讨论】:

  • 您可能希望使用 Fiddler 来捕获底层错误。当我有一个参数错误时,我遇到了这个错误。通过 Fiddler 记录 IP 数据包,我能够看到名为 bad 参数的潜在错误。 Google API DotNet 客户端Issue 480 要求增强 API 以返回包含底层错误的对象。如果您认为它可以帮助您将来进一步调试,请投赞成票。
  • 你成功通过了这个错误吗?
  • @Briller:还没有。如果您发现实际问题,请在此处分享。
  • @DCI :我发现这是通用错误,通常出现在另一个异常之后。在这里查看我的评论:stackoverflow.com/questions/26204080/…

标签: youtube-api


【解决方案1】:

您可以尝试以下更改:

发件人:

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

收件人:

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

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

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

【讨论】:

  • 当我按照您的建议进行更改时,我收到“响应状态代码不表示成功:401(未经授权)。”和“值不能为空。参数名称:baseUri”。
  • 我正在从浏览的文件中读取内容类型。我尝试使用 .mp4 文件。因此,在这种情况下,内容类型作为 video/mp4 传递。我也尝试通过 video/*,仍然是同样的问题。
  • 我修改了答案以解决状态码 401 错误的可能原因。
  • 很久以后,我正在尝试解决这个问题。我尝试了你所有的提示。但不工作。
猜你喜欢
  • 2014-12-12
  • 1970-01-01
  • 2012-10-07
  • 2016-08-27
  • 2017-06-14
  • 2014-10-13
  • 2014-12-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多