You need to enable JavaScript to run this app. C#使用Google Sheets API v4获取工作表列表出现400错误请求问题
优惠活动
大模型
产品
解决方案
定价
更多

C#使用Google Sheets API v4获取工作表列表出现400错误请求问题

问题原因

你遇到的400错误核心原因是路径参数未被正确填充:从调试输出可见,请求的RestPath仍保留{spreadsheetId}占位符,没有被替换为实际的表格ID,导致最终请求的URL无效。
该问题90%以上是你自定义的ProxySupportedHttpClientFactory导致的:Google官方的.NET客户端库默认会在发起请求前自动完成路径参数替换、API密钥拼接等操作,自定义HttpClientFactory如果改写了请求构建流程,很容易跳过这一步。

解决步骤

1. 先移除自定义HttpClientFactory验证

先注释掉HttpClientFactory的配置,用默认配置测试是否能正常请求:

var sheetsService = new SheetsService(new BaseClientService.Initializer()
{
    ApplicationName = ApplicationName,
    ApiKey = API_KEY,
    // 先注释掉自定义的HttpClientFactory测试
    // HttpClientFactory = new ProxySupportedHttpClientFactory(),
});

测试如果可以正常返回结果,就可以确认是自定义HttpClientFactory的问题。

2. 正确配置代理(如果必须使用代理)

不要通过自定义HttpClientFactory的方式配置代理,改用官方推荐的HttpClientInitializer配置方式,示例如下:

var proxy = new WebProxy("你的代理地址", 端口号)
{
    Credentials = CredentialCache.DefaultCredentials
    // 如果代理需要账号密码,单独设置Credentials即可
};
var httpClientHandler = new HttpClientHandler
{
    Proxy = proxy,
    UseProxy = true
};

var sheetsService = new SheetsService(new BaseClientService.Initializer()
{
    ApplicationName = ApplicationName,
    ApiKey = API_KEY,
    HttpClientInitializer = httpClientHandler
});

3. 可选:显式指定返回字段

如果只需要获取所有工作表名称,可以显式指定返回字段减少请求体积:

SpreadsheetsResource.GetRequest request = sheetsService.Spreadsheets.Get(spreadsheetId);
// 只返回工作表的标题字段
request.Fields = "sheets.properties.title";
Data.Spreadsheet response = request.Execute();

// 遍历输出所有工作表名称
foreach (var sheet in response.Sheets)
{
    Console.WriteLine(sheet.Properties.Title);
}

内容的提问来源于stack exchange,提问作者Ceri Turner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 06:06:02