Google Ads API 客户端库提供了多种配置设置,您可以使用这些设置来自定义库行为。
在运行时配置库
配置客户端库的首选方式是在运行时初始化 GoogleAdsConfig 对象:
GoogleAdsConfig config = new GoogleAdsConfig()
{
OAuth2Mode = OAuth2Flow.APPLICATION,
OAuth2ClientId = "INSERT_CLIENT_ID.apps.googleusercontent.com",
OAuth2ClientSecret = "INSERT_CLIENT_SECRET",
OAuth2RefreshToken = "INSERT_REFRESH_TOKEN"
};
GoogleAdsClient client = new GoogleAdsClient(config);
替代配置选项
该库还提供了用于加载配置设置的其他选项。如需启用这些功能,请在项目中添加对 Google.Ads.GoogleAds.Extensions 软件包的 NuGet 引用。
如果您使用上述任一选项,系统不会自动提取配置设置;您必须明确加载这些设置,如下面部分所示。从外部文件或数据流加载设置时,请务必处理文件 I/O 异常(例如 FileNotFoundException 或 UnauthorizedAccessException)。
使用 App.config
所有特定于 Google Ads API 的设置都存储在 App.config 文件的 GoogleAdsApi 节点中。典型配置 App.config 如下:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="GoogleAdsApi"
type="System.Configuration.DictionarySectionHandler" />
</configSections>
<GoogleAdsApi>
<!-- Set the service timeout in milliseconds. -->
<add key="Timeout" value="2000" />
<!-- Proxy settings for library. -->
<add key="ProxyServer" value="http://localhost:8888" />
<add key="ProxyUser" value="" />
<add key="ProxyPassword" value="" />
<add key="ProxyDomain" value="" />
<!-- OAuth2 settings -->
<add key="OAuth2Mode" value="APPLICATION" />
<add key="OAuth2ClientId"
value="INSERT_CLIENT_ID.apps.googleusercontent.com" />
<add key="OAuth2ClientSecret" value="INSERT_CLIENT_SECRET" />
<add key="OAuth2RefreshToken" value="INSERT_REFRESH_TOKEN" />
</GoogleAdsApi>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
</configuration>
如需从 App.config 文件加载配置设置,请对 GoogleAdsConfig 对象调用 LoadFromDefaultAppConfigSection 方法:
GoogleAdsConfig config = new GoogleAdsConfig();
config.LoadFromDefaultAppConfigSection();
GoogleAdsClient client = new GoogleAdsClient(config);
指定单独的 App.config 文件
如果您不想让 App.config 过于杂乱,可以使用 configSource 属性将特定于库的配置移到自己的配置文件中:
在
App.config中指定configSource。修改App.config以引用外部配置文件:<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="GoogleAdsApi" type="System.Configuration.DictionarySectionHandler" /> </configSections> <GoogleAdsApi configSource="GoogleAdsApi.config" /> </configuration>指定配置文件的内容。创建另一个配置文件,其名称与您在
configSource(GoogleAdsApi.config) 中指定的名称相同,并将GoogleAdsApi配置节点从App.config移到此文件中:<?xml version="1.0" encoding="utf-8" ?> <GoogleAdsApi> <!-- More settings. --> </GoogleAdsApi>更新
.csproj中的 build 规则。在项目中添加新的配置文件,并将其 Copy to Output Directory 属性设置为 Copy always。重新构建并运行项目,以便应用从新的配置文件中获取值。
使用自定义 JSON 文件
您可以使用 IConfigurationRoot 实例来配置客户端库。
创建一个 JSON 文件
创建一个名为 GoogleAdsApi.json 且结构与 App.config 文件类似的 JSON 文件:
{
"Timeout": "2000",
"ProxyServer": "http://localhost:8888",
"ProxyUser": "",
"ProxyPassword": "",
"ProxyDomain": "",
"OAuth2Mode": "APPLICATION",
"OAuth2ClientId": "INSERT_CLIENT_ID.apps.googleusercontent.com",
"OAuth2ClientSecret": "INSERT_CLIENT_SECRET",
"OAuth2RefreshToken": "INSERT_REFRESH_TOKEN"
}
加载配置
接下来,将 JSON 文件加载到 IConfigurationRoot 中:
ConfigurationBuilder builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("GoogleAdsApi.json");
IConfigurationRoot configRoot = builder.Build();
GoogleAdsConfig config = new GoogleAdsConfig();
config.LoadFromConfigurationRoot(configRoot);
GoogleAdsClient client = new GoogleAdsClient(config);
使用 settings.json
此处的流程与使用自定义 JSON 文件类似,只是密钥应位于名为 GoogleAdsApi 的部分中:
{
"GoogleAdsApi": {
"OAuth2Mode": "APPLICATION",
"OAuth2ClientId": "INSERT_CLIENT_ID.apps.googleusercontent.com",
"OAuth2ClientSecret": "INSERT_CLIENT_SECRET",
"OAuth2RefreshToken": "INSERT_REFRESH_TOKEN"
}
}
接下来,从应用的 IConfiguration 实例(例如,由 ASP.NET Core 注入或使用 ConfigurationBuilder 构建)中提取 GoogleAdsApi 部分:
IConfigurationSection section = configuration.GetSection("GoogleAdsApi");
GoogleAdsConfig config = new GoogleAdsConfig();
config.LoadFromConfigurationSection(section);
GoogleAdsClient client = new GoogleAdsClient(config);
或者,您也可以使用 config.LoadFromSettingsJson(filePath, "GoogleAdsApi") 通过路径直接加载 settings.json 文件,或使用 config.TryLoadFromEnvironmentFilePath 从 GOOGLE_ADS_CONFIGURATION_FILE_PATH 环境变量 (EnvironmentVariableNames.CONFIG_FILE_PATH) 加载 settings.json 文件。
使用环境变量
您还可以使用环境变量初始化 GoogleAdsClient:
GoogleAdsConfig config = new GoogleAdsConfig();
config.LoadFromEnvironmentVariables();
GoogleAdsClient client = new GoogleAdsClient(config);
请参阅受支持的环境变量的完整列表。
使用通用流
您还可以从通用流(包括加密流)加载配置或部分配置:
GoogleAdsConfig config = new GoogleAdsConfig()
{
// Set some configuration properties in code.
OAuth2Mode = OAuth2Flow.SERVICE_ACCOUNT,
};
// Load your encrypted data from a file and dispose of the streams properly.
using (CryptoStream strm = GetEncryptedCredentialsStream())
using (StreamReader rdr = new StreamReader(strm))
{
// Configure the OAuth credentials from the encrypted stream.
config.LoadOAuth2SecretsFromStream(rdr);
}
GoogleAdsClient client = new GoogleAdsClient(config);
配置字段
以下部分列出了 Google Ads .NET 库支持的设置。
互联网连接设置
Timeout:使用此键可设置服务超时时间(以毫秒为单位)。默认值根据googleads_grpc_service_config.json中的method_config/timeout设置来确定。如果您需要强制缩短 API 调用的最长时间限制,请设置较低的值。您可以将超时时间设置为 2 小时或更长时间,但对于运行时间极长的请求,API 仍可能会超时并返回DEADLINE_EXCEEDED错误。ProxyServer:如果您使用代理连接到互联网,请将此属性设置为 HTTP 代理服务器网址。ProxyUser:将此项设置为您需要用于针对代理服务器进行身份验证的用户名。如果不需要用户名,请将此字段留空。ProxyPassword:如果您为ProxyUser设置了值,请将此值设置为ProxyUser的密码。ProxyDomain:如果您的代理服务器需要设置网域,请将此项设置为ProxyUser的网域。MaxReceiveMessageLengthInBytes:使用此设置可增加客户端库可处理的 API 响应的最大大小。默认值为 64 MB。MaxMetadataSizeInBytes:使用此设置可增加客户端库可处理的 API 错误响应的最大大小。默认值为 16 MB。
调整 MaxReceiveMessageLengthInBytes 和 MaxMetadataSizeInBytes 设置可修正某些 ResourceExhausted 错误。这些设置可解决以下形式的错误:
Status(StatusCode="ResourceExhausted",Detail="Received
message larger than max (423184132 versus 67108864)"
在此示例中,错误是由于消息大小 (423184132 bytes) 大于库可处理的大小 (67108864 bytes) 而导致的。请将 MaxReceiveMessageLengthInBytes 增加到 500000000,以避免此错误。请注意,此错误还表明您的代码处理了一个非常大的响应对象(例如一个大的 SearchGoogleAdsResponse)。这可能会对代码的性能产生影响,因为 .NET 的大对象堆。如果这成为性能问题,您可能需要探索如何重新组织 API 调用或重新设计应用的部分内容。
OAuth2 设置
使用 OAuth 2.0 授权您对 Google Ads API 服务器的调用时,您应设置以下配置键:
AuthorizationMethod:设置为OAuth2。OAuth2Mode:设置为APPLICATION或SERVICE_ACCOUNT。OAuth2ClientId:将此值设置为您的 OAuth 2.0 客户端 ID。OAuth2ClientSecret:将此值设置为您的 OAuth 2.0 客户端密钥。OAuth2Scope:如果您想为多个 API 授权 OAuth 2.0 令牌,请将此值设置为不同的范围。此设置是可选的。UseApplicationDefaultCredentials:将此值设置为true可使用应用默认凭证进行身份验证(在Google.Ads.GoogleAdsv24.1.0及更高版本中受支持;config.LoadFromEnvironmentVariables()会读取不带前缀的USE_APPLICATION_DEFAULT_CREDENTIALS环境变量)。Credentials:(仅限运行时,在v27.0.0及更高版本中受支持)在运行时将预先构建的ICredential或GoogleCredential实例直接注入到GoogleAdsConfig中。
如果您使用的是 OAuth2Mode == APPLICATION,则需要设置以下额外的配置键:
OAuth2RefreshToken:如果您想重复使用 OAuth 2.0 令牌,请将此值设置为预生成的 OAuth 2.0 刷新令牌。此设置是可选的。OAuth2RedirectUri:将此值设置为 OAuth 2.0 重定向网址。此设置是可选的。
如需了解详情,请参阅以下指南:
如果您使用的是 OAuth2Mode == SERVICE_ACCOUNT,则需要设置以下额外的配置键:
OAuth2SecretsJsonPath:将此值设置为 OAuth 2.0 JSON 密钥文件的路径。OAuth2PrnEmail:使用 Google Workspace 网域范围的委托时,将此值设置为您要模拟的账号的电子邮件地址。此设置是可选的。
如需了解详情,请参阅 OAuth 服务账号流程指南。
交通设置
UseGrpcCore:将此设置设为true可使用Grpc.Core库作为底层传输层。请参阅使用Grpc.Core库。
Google Ads API 设置
以下设置是 Google Ads API 专有的:
DeveloperToken:在v27.3.0及更高版本中为可选 (GOOGLE_ADS_DEVELOPER_TOKEN)。开发者令牌已于 2026 年 9 月 9 日停用;在 API 服务器上,访问权限级别由您的 Google Cloud 项目决定,与客户端库版本无关,并且 API 服务器会忽略developer-token标头(直到未来的某个 Google Ads API 主要版本拒绝该标头)。如需从配置中省略或移除DeveloperToken,请使用Google.Ads.GoogleAdsv27.3.0或更高版本,该版本移除了本地客户端DeveloperToken验证(早期版本要求DeveloperToken不为空才能进行本地验证)。LoginCustomerId:这是授权客户在请求中使用的客户 ID,不含连字符 (-)。LinkedCustomerId:只有在通过 Google Ads 界面中的关联账号授予权限时,此标头才对更新实体资源(Google Ads API 中的AccountLink资源)的方法是必需的。将此值设置为更新指定客户 ID 的资源的数据提供方的客户 ID。应不含连字符 (-)。 详细了解关联的账号。