Не удалось запустить браузер, когда GoogleDriveApplication размещен на IIS Server - PullRequest
0 голосов
/ 28 сентября 2018

Я работаю с Google Drive API v3 локально, он работает для создания token.json, когда я получаю сообщение об ошибке на сервере IIS:

  • Доступ запрещен

Описание: во время выполнения текущего веб-запроса произошло необработанное исключение.Пожалуйста, просмотрите трассировку стека для получения дополнительной информации об ошибке и о том, где она возникла в коде.

Exception Details: System.ComponentModel.Win32Exception: Access is denied

Ошибка источника:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace: 
[Win32Exception (0x80004005): Access is denied]

System.Diagnostics.Process.StartWithShellExecuteEx (ProcessStartInfo startInfo) +604 System.Diagnostics.Process.Start (ProcessStartInfo startInfo) +60 Google.Apis.Auth.OAuth2.d__14.MoveNext () + 261

[NotSupportedException: не удалось запустить браузер с "https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&response_type=code&client_id=xxxxxxxx.apps.googleusercontent.com&redirect_uri=http%3A%2F%2F127.0.0.1%3A61855%2Fauthorize%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive" для авторизации. Подробности см. Во внутреннем исключении.] Google.Apis.Auth.OAuth2.d__14.MoveNext () +1011 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () +31 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (задача задачи) 60. Google.d__8.MoveNext () +716 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () +31 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (задача-задача) +60 Google.Apis.Auth.OAee.__.System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () +31 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (Задача) +60 Google.Apis.Auth.OAuth2.d__1.MoveNext () + 435

[AggregateException: произошла одна или несколько ошибок.] System.Threading.Tasks.Task 1.GetResultCore(Boolean waitCompletionNotification) +4757412 TestGoogleDrive.Controllers.HomeController.Testcode() in C:\Users\xxxxxxx\source\repos\GoogleDriveTestApplication\TestGoogleDrive\Controllers\HomeController.cs:42 lambda_method(Closure , ControllerBase , Object[] ) +87 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary 2 параметра) +35 System.Web.Mvc.Async. <> C.b__9_0 (IAsyncResult asyncResult, ActionInvocation innerInvokeState) +39 System.Web.Mvc.Async.WrappedAsyncResult 2.CallEndDelegate(IAsyncResult asyncResult) +77 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +42 System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__11_0() +72 System.Web.Mvc.Async.<>c__DisplayClass11_1.<InvokeActionMethodFilterAsynchronouslyRecursive>b__2() +387 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +42 System.Web.Mvc.Async.<>c__DisplayClass3_6.<BeginInvokeAction>b__3() +50 System.Web.Mvc.Async.<>c__DisplayClass3_1.<BeginInvokeAction>b__5(IAsyncResult asyncResult) +188 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +38 System.Web.Mvc.<>c.<BeginExecuteCore>b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) +26 System.Web.Mvc.Async.WrappedAsyncVoid 1.CallEndDelegate (IAsyncResult as73 + .73) .73)Mvc.Controller.EndExecuteCore (IAsyncResult asyncResult) +52 System.Web.Mvc.Async.WrappedAsyncVoid 1.CallEndDelegate(IAsyncResult asyncResult) +39 System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +38 System.Web.Mvc.<>c.<BeginProcessRequest>b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) +40 System.Web.Mvc.Async.WrappedAsyncVoid 1.CallEndDelegate (IAsyncResult asyncResult) +73 System.Web..CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute () +602 System.Web.HttpApplication.ExecuteStepImpl (шаг IExecutionStep) +195 System.Web.HttpApplication * Execute * 10* Это мои данные Google App:

{ "installed": { "client_id": "xxxxxxxxxx.apps.googleusercontent.com", "project_id": "xxxxxxxxxxxx", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://www.googleapis.com/oauth2/v3/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_secret": "xxxxxxxxxxxxxxxxxx", "redirect_uris": [ "urn:ietf:wg:oauth:2.0:oob", "http://localhost" ] } }

Это мой код:

string[] Scope = { DriveService.Scope.Drive };
string ApplicationName = "testApplication";
UserCredential credential;
using (var stream = new FileStream(Server.MapPath("~/App_Data/credentials.json"), FileMode.Open, FileAccess.Read))
{
    string credPath = Server.MapPath("~/App_Data/token.json");
    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
        GoogleClientSecrets.Load(stream).Secrets,
        Scope,
        "user",
        CancellationToken.None,
        new FileDataStore(credPath, true)).Result;
    // Console.WriteLine("Credential file saved to: " + credPath);
}
var service = new DriveService(new BaseClientService.Initializer() {
        HttpClientInitializer = credential,
        ApplicationName = ApplicationName,
    });

1 Ответ

0 голосов
/ 01 октября 2018

Пожалуйста, попробуйте так: public async System.Threading.Tasks.Task UploadFileAsync () {try {

            // Create the service using the client credentials.
         var json=   HttpContext.Current.Server.MapPath("~/credentials.json");
            UserCredential credential;
            using (var stream = new FileStream(json, FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new[] { DriveService.Scope.Drive },
                    "user", CancellationToken.None, new FileDataStore("Audio.files"));
            };
            var service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "YourAppName"
            });
            var uploadFilepath = HttpContext.Current.Server.MapPath("~/Content/filename.flac");
            var uploadStream = new System.IO.FileStream(uploadFilepath,
                                                        System.IO.FileMode.Open,
                                                        System.IO.FileAccess.Read);
            // Get the media upload request object.
            var insertRequest = service.Files.Create(
                  new Google.Apis.Drive.v3.Data.File
                  {
                      Name = "Filename.flac",
                  },
                  uploadStream,
                  "audio/flac");


            var task = insertRequest.UploadAsync();
            await task.ContinueWith(t =>
             {
                 // Remeber to clean the stream.
                 uploadStream.Dispose();
             });
            var result = task.Result;
        }
        catch (Exception EX)
        {

        }
    }
...