C#调用Google Sheets API获取凭证时遇「无法识别凭证类型」错误求助
Google Sheets API凭证创建错误排查
使用Google API获取凭证时遇到问题,查阅大量旧帖仍未找到解决方案,目标是将指定电子表格中的数据导入到DataTable中。
我的代码
static readonly string[] Scopes = { SheetsService.Scope.Spreadsheets }; static readonly string ApplicationName = "Dot Tutorials"; static readonly string sheet = "Arkusz1"; static readonly string SpreadsheetId = "1IEvv4enfouBXrGEVLTKeQNYTJIzQHmRNyKTxKAxEAfg"; static SheetsService service; GoogleCredential credential; //Reading Credentials File... using (var stream = new FileStream("secret.json", FileMode.Open, FileAccess.Read)) { credential = GoogleCredential.FromStream(stream) .CreateScoped(Scopes); } // Creating Google Sheets API service... service = new SheetsService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, });
下载的secret.json内容
{ "installed": { "client_id": "1087609048092-hdh5ku57kaamha72o7t3tdtkb62vq5ur.apps.googleusercontent.com", "project_id": "excellent-well-151116", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_secret": "*********hidden my secret code*******", "redirect_uris": [ "http://localhost" ] } }
运行时错误
System.InvalidOperationException: 'Error creating credential from JSON or JSON parameters. Unrecognized credential type .'
解决方案
你的secret.json是桌面应用类型的OAuth客户端凭证(包含installed字段),这类凭证不能直接通过GoogleCredential.FromStream初始化,因为它需要走OAuth 2.0授权码流程获取用户授权令牌,而非服务账号的直接认证方式。
修改后的代码
static readonly string[] Scopes = { SheetsService.Scope.Spreadsheets }; static readonly string ApplicationName = "Dot Tutorials"; static readonly string sheet = "Arkusz1"; static readonly string SpreadsheetId = "1IEvv4enfouBXrGEVLTKeQNYTJIzQHmRNyKTxKAxEAfg"; static SheetsService service; // 处理用户授权并获取凭证 UserCredential credential; using (var stream = new FileStream("secret.json", FileMode.Open, FileAccess.Read)) { // 指定令牌缓存路径,避免重复授权 string credPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), ".credentials/sheets-dotnet-tutorial.json"); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.FromStream(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; } // 创建Sheets服务实例 service = new SheetsService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, });
额外注意事项
- NuGet包检查:确保项目已安装
Google.Apis.Sheets.v4和Google.Apis.Auth两个NuGet包,版本保持一致。 - 文件路径设置:将
secret.json的属性设置为「复制到输出目录」(如果文件不在程序运行目录下),确保程序能读取到该文件。 - 电子表格权限:确保你的Google账号有权访问目标电子表格,可通过共享功能将表格权限开放给该账号,或设置表格为公开可查看/编辑。
- 授权流程:第一次运行代码会弹出浏览器,引导你登录Google账号并授权应用访问Sheets数据,授权后令牌会缓存到指定路径,后续运行无需重复授权。
内容的提问来源于stack exchange,提问作者Adam Zbudniewek
相关产品推荐
相关产品推荐

