我希望使用youtube上传数据api上传视频,但不幸的是,当我尝试上传视频时,它会生成一个任务被取消的错误await videosInsertRequest.UploadAsync();
在我的代码中,我已经应用了AsyncTimeout属性,我的操作是
[AsyncTimeout(3600000)]
public async Task <ActionResult> YouTube(int? Id)
{
// await Run();
var dbListVideos = db.Videos.Where(v => v.Id == Id).ToList();
await YouTubeHandler.UploadVideos(dbListVideos);
return View();
}
它会调用YouTube的API
public static async Task UploadVideos(List<MyVideo> videosList)
{
foreach (var vid in videosList)
{
await Upload(vid);
}
}
public static async Task Upload(MyVideo newVideo)
{
UserCredential credential;
using (var stream = new FileStream("G:\\client_secret_783534382593-0cn4gm229raqq97kdu0ghsj9hqfsc5o1.apps.googleusercontent.com.json", FileMode.Open, FileAccess.Read))
{
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
);
}
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
});
Video video = new Video();
video.Snippet = new VideoSnippet();
video.Snippet.Title = newVideo.Title;
video.Snippet.Description = newVideo.Description;
video.Snippet.Tags = new string[] { newVideo.Tags };
video.Snippet.CategoryId = newVideo.Category; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
video.Status = new VideoStatus();
video.Status.PrivacyStatus = newVideo.PrivacyStatus; // or "private" or "publi
var filePath = newVideo.Path; // Replace with path to actual movie file.
// YouTubeHandler t = new YouTubeHandler();
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();
}
}
static 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;
}
}
static void videosInsertRequest_ResponseReceived(Video video)
{
Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);
}
}
}
任何人都可以帮助我,因为我是ASP和异步任务的新手
答案 0 :(得分:4)
我找到了这个问题的解决方案您需要在使用服务之前设置超时。
YouTubeService youtubeService = new YouTubeService(initializer);
youtubeService.HttpClient.Timeout= TimeSpan.FromMinutes(60);
这将解决任务取消问题。谢谢