使用 Oauth2 和 Google Drive API 的 c# 异常(使用 4.0 .Net)

标签 c# .net oauth-2.0 google-api-dotnet-client

我正在使用 http://www.daimto.com/google-oauth2-csharp/ 的代码示例这将允许我连接到 google drive api 并使用 oauth2 获得授权。我下载了包含我的客户端 ID 和客户端密码的 .json 文件,并将其放在\bin\debug 输出文件夹(以及其他一些出于绝望的地方),当代码继续打开该文件时,它会导致异常说“流句柄”引发了“System.Object.DisposeException”类型的异常

单步执行时代码在此处(在凭据行)抛出异常:

using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                GoogleWebAuthorizationBroker.Folder = "Tasks.Auth.Store";
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                new[] { DriveService.Scope.Drive,
                DriveService.Scope.DriveFile },
                "user",
                CancellationToken.None,
                new FileDataStore("Drive.Auth.Store")).Result;
            }

这可能是我尝试过的第 4 个或第 5 个代码示例,但它们似乎都不起作用。真是令人沮丧。

最佳答案

我可以看出该教程已经过时了。我不确定为什么您无法使用流阅读器读取文件。但我认为您会发现这段代码更清晰、更容易理解。

string _client_id = "from apis console";
string _client_secret = "frome apis console";
string[] scopes = new string[] {DriveService.Scope.Drive,
                                DriveService.Scope.DriveFile };
// 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 = _client_id,
                                                                 ClientSecret = _client_secret },
                                                    scopes,
                                                    Environment.UserName,
                                                    CancellationToken.None,
                                                new FileDataStore("Daimto.GooglePlus.Auth.Store")
                                                    ).Result;

我会尽快更新该教程。

关于使用 Oauth2 和 Google Drive API 的 c# 异常(使用 4.0 .Net),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25921628/

相关文章:

c# - MVC Owin 提供程序 key 更改

c# - VS 2017 RC asp.net core system.net.http冲突问题

c# - HRESULT : 0x80040154 (REGDB_E_CLASSNOTREG), 错误,我的网站位于 azure 云上

c# - Linq 没有返回所有需要的数据

c# - 序列化 LINQ to SQL 类时出现循环引用异常

.net - 全局程序集缓存查看器工具(Viewer)

spring - oauth2 中的授权端点未附带刷新 token

oauth-2.0 - 缺少必需的参数 : client_id

c# - ASPX - FindControl(string) 找到控件但不是它的值

c# - .NET 中 Xml 序列化失败的场景