如何解决Google Drive API异常:‘从JSON创建凭据失败,未知凭据类型’
解决Google Drive API在.NET Rhino插件中的JSON凭据错误
核心问题
你使用的是桌面应用类型的OAuth客户端凭据JSON,但GoogleCredential.FromFile()方法仅适用于加载服务账号密钥或已保存的用户授权令牌,无法直接解析客户端ID/Secret格式的JSON文件——这就是报错的根源。
修复方案
1. 替换凭据加载逻辑
桌面应用需要通过OAuth 2.0交互式授权流程获取用户权限,改用GoogleWebAuthorizationBroker处理授权:
using Google.Apis.Auth.OAuth2; using Google.Apis.Drive.v3; using Google.Apis.Services; using Google.Apis.Util.Store; using System.IO; using System.Threading; string[] scopes = { DriveService.Scope.DriveFile }; string credentialsFilePath = "D:\\credentials.json"; // 用于保存授权令牌,避免每次启动都重复登录 string tokenStorageDir = "D:\\RhinoDriveAuthTokens"; UserCredential credential; using (var stream = new FileStream(credentialsFilePath, FileMode.Open, FileAccess.Read)) { credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, scopes, "user", CancellationToken.None, new FileDataStore(tokenStorageDir, true)).Result; } // 创建Drive服务实例 var driveService = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Rhino Drive Upload Plugin" // 需与Google Cloud项目中的应用名称一致 });
2. 修正其他常见错误
- 文件夹ID而非名称:代码中
Parents = new[] { "API_Test" }错误,必须使用Drive文件夹的唯一ID。打开你的API_Test文件夹,地址栏末尾的字符串就是ID(如1AbCdEfGhIjKlMnOpQrStUvWxYz),替换成该值。 - 文件路径与权限:确保
credentials.json路径正确,且Rhino插件运行时有权限读取该文件(避免放在C:\Program Files等系统保护目录)。 - NuGet包版本:确保安装最新版的
Google.Apis.Drive.v3和Google.Apis.AuthNuGet包,版本不匹配可能引发异常。
完整修复代码
using Google.Apis.Auth.OAuth2; using Google.Apis.Drive.v3; using Google.Apis.Services; using Google.Apis.Util.Store; using System.IO; using System.Threading; // 配置参数 string credentialsPath = "D:\\credentials.json"; string tokenStorePath = "D:\\RhinoDriveAuth"; string targetFolderId = "替换为你的API_Test文件夹ID"; string uploadFilePath = "D:\\Points.txt"; // 获取授权凭据 UserCredential credential; using (var stream = new FileStream(credentialsPath, FileMode.Open, FileAccess.Read)) { credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, new[] { DriveService.Scope.DriveFile }, "user", CancellationToken.None, new FileDataStore(tokenStorePath, true)).Result; } // 初始化Drive服务 var driveService = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Rhino Drive Uploader" }); // 准备文件元数据 var fileMetadata = new Google.Apis.Drive.v3.Data.File() { Name = Path.GetFileName(uploadFilePath), Parents = new[] { targetFolderId } }; // 执行上传 using (var stream = new FileStream(uploadFilePath, FileMode.Open)) { var uploadRequest = driveService.Files.Create(fileMetadata, stream, "text/plain"); uploadRequest.Fields = "id"; var uploadResult = uploadRequest.Upload(); if (uploadResult.Status == Google.Apis.Upload.UploadStatus.Completed) { // 上传成功,可在Rhino中提示 // RhinoApp.WriteLine($"文件上传完成,ID:{uploadRequest.ResponseBody.Id}"); } else { // 处理错误 // RhinoApp.WriteLine($"上传失败:{uploadResult.Exception.Message}"); } }
内容的提问来源于stack exchange,提问作者bBen1997
相关产品推荐
相关产品推荐

