Я пытаюсь загрузить видео на мой счет YouTube с помощью следующего кода в моем ActionResult в моем asp.net MVC проекта:ASP.net MVC: Доступ к Google GoogleWebAuthorizationBroker возвращается ошибка доступа
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Upload([Bind(Include = " Title, Description")] HttpPostedFileBase uploadFile, Videos videos)
{
var credential = AuthYouTube();
YouTubeService youtubeService = new YouTubeService(new
YouTubeService.Initializer()
{
ApplicationName = "app-name",
HttpClientInitializer = credential
});
// Do Stuff with the video here.
}}
AuthYouTube() выглядит следующим образом (тот же контроллер):
public UserCredential AuthYouTube()
{
string filePath = Server.MapPath("~/Content/YT/client_secret.json");
UserCredential credential;
try{
using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
// This OAuth 2.0 access scope allows for full read/write access to the
// authenticated user's account.
new[] { YouTubeService.Scope.Youtube },
"[email protected]",
CancellationToken.None,
new FileDataStore(Server.MapPath("~/Content/YT"),true)
).Result;
};
return credential;
}
catch(EvaluateException ex)
{
Console.WriteLine(ex.InnerException);
return null;
}
}
Я сохранил свою client_secret.json, что я скачал из консоли Google Developer внутри [проект]/содержания/YT. (Также попробовал в папке/App_Data
При загрузке отладчика отображается сообщение folowwing:.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ComponentModel.Win32Exception: Access is denied
Место, где встретилась ошибка:
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
StackStrace:
[Win32Exception (0x80004005): Access is denied]
Microsoft.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +115
Microsoft.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccess(Task task) +78
Google.Apis.Auth.OAuth2.<AuthorizeAsync>d__1.MoveNext() in C:\Users\mdril\Documents\GitHub\google-api-dotnet-client\Src\GoogleApis.Auth.DotNet4\OAuth2\GoogleWebAuthorizationBroker.cs:59
[AggregateException: One or more errors occurred.]
System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification) +4472256
Project.Controllers.VideosController.AuthYouTube() in d:\dev\Development\project\project\Controllers\VideosController.cs:133
project.Controllers.VideosController.Upload(HttpPostedFileBase uploadFile, Videos videos) in d:\dev\project\project\Controllers\VideosController.cs:71
В чем причина этого? - Google API? - папка/права IIS?
Update 01-02-2016
Может быть, какая-то ошибка доступа на стороне API? Если нет, может кто-нибудь, пожалуйста, предоставьте мне шаги, необходимые для прав IIS, все равно получите сообщение об ошибке после предоставления прав доступа к папке.
Выполнение следующего кода. Создайте папку как предназначено внутри моего App_Data, но также возвращает ту же ошибку «Доступ запрещен». Папка пуста.
var path = HttpContext.Current.Server.MapPath("~/App_Data/Drive.Api.Auth.Store");
// 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(path,true)).Result;
Не могли бы вы объяснить, как это работает?
добавьте проверку, что он может найти файл filePath и получить к нему доступ. – DaImTo
@dalmo Сделал это allready. Происходит путь filepath (stream). Больше действий? – RunnicFusion
убедитесь, что у вас есть доступ к записи в этот каталог. звучит для меня как filedatastore can not create file. Предоставьте права администратора пользователю IIS. – DaImTo