Я пытаюсь загрузить видео на свой канал YouTube с помощью веб-формы ASP.NET. Я создал учетную запись разработчика и tested it working using JavaScript based solution, которая требует входа в систему для загрузки видео.redirect_uri_mismatch в API Google в ASP.NET
Я хочу, чтобы пользователи моего сайта загружали видео прямо на мой канал, и каждый auth должен быть в коде позади, пользователю не следует запрашивать логин. Для этого я написал следующий класс:
public class UploadVideo
{
public async Task Run(string filePath)
{
string CLIENT_ID = "1111111111111111111111.apps.googleusercontent.com";
string CLIENT_SECRET = "234JEjkwkdfh1111";
var youtubeService = AuthenticateOauth(CLIENT_ID, CLIENT_SECRET, "SingleUser");
var video = new Video();
video.Snippet = new VideoSnippet();
video.Snippet.Title = "Default Video Title";
video.Snippet.Description = "Default Video 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 = "unlisted"; // or "private" or "public"
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();
}
}
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);
}
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;
}
}
}
Теперь с помощью этого класса в Page_Load() из default.aspx, как указано ниже:
protected void Page_Load(object sender, EventArgs e)
{
try
{
string path = "C:/Users/abhi/Desktop/TestClip.mp4";
new UploadVideo().Run(path).Wait();
}
catch (AggregateException ex)
{
//catch exceptions
}
}
Когда я запускаю этот (default.aspx) страницу, я см http://localhost:29540/default.aspx закрутки, так что я использовал их на Google Developer Console, как указано ниже:
После запуска http://localhost:29540/default.aspx открывает новый т аб, который отображает сообщение об ошибке «redirect_uri_mismatch», как указано ниже:
На данный момент, если я смотрю в адрес браузера, я вижу redirect_uri установлен в http://localhost:37294/authorize и я просто вручную изменить это http://localhost:29540/default.aspx, который генерирует маркер.
Итак, можете ли вы предложить, где внести изменения в вышеприведенный код, чтобы запрос uri правильно заполнялся со стороны моего приложения.
Благодарю вас, я понял, что иногда вы должны положить «/» в конце URL-адреса, а иногда нет. Я потерял несколько часов, потому что это глупость. – ajmena