开始使用
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
本指南简要介绍了如何开始使用 Google Ads API .NET 库。
安装
客户端库二进制文件通过 NuGet 进行分发。在项目中添加对 Google.Ads.GoogleAds
软件包的 NuGet 引用,以使用客户端库。
设置授权
如需授权 API 调用,您需要向库指定客户端 ID、客户端密钥、刷新令牌和开发者令牌。
如果您需要生成凭据
如果您已有凭据
- 从 GitHub 中的
App.config
文件中复制 GoogleAdsApi
节点和 configSections
节点下的 GoogleAdsApi
部分,然后将其粘贴到 App.config
/ Web.config
文件中。如果您使用 NuGet 安装了该软件包,这些节点将自动插入到您的 App.config
/ Web.config
文件中。
- 在应用的
App.config
/ Web.config
中添加开发者令牌、客户端 ID、客户端密钥和刷新令牌。
GitHub 中包含的 App.config
文件有详细的文档记录,但您也可以参阅配置指南了解更多信息,并使用其他方式来配置客户端库,例如环境变量。
进行 API 调用
客户端库的基本用法如下:
// Create a Google Ads client.
GoogleAdsClient client = new GoogleAdsClient();
// Create the required service.
CampaignServiceClient campaignService =
client.GetService(Services.V21.CampaignService);
// Make more calls to service class.
创建 GoogleAdsClient 实例
Google Ads API .NET 库中最重要的类是 GoogleAdsClient
类。借助此功能,您可以创建预配置的服务类,用于进行 API 调用。GoogleAdsClient
提供了一个默认构造函数,用于使用应用的 App.config
/ Web.config
中指定的设置创建用户对象。如需了解配置选项,请参阅配置指南。
// Create a new GoogleAdsClient with the App.config settings.
GoogleAdsClient user = new GoogleAdsClient();
创建服务
GoogleAdsClient
提供了一种可用于创建广告服务的 GetService
方法。
CampaignServiceClient campaignService = client.GetService(Services.V21.CampaignService);
// Now make calls to CampaignService.
我们提供了一个 Services
类,用于枚举所有受支持的 API 版本和服务。创建服务时,GetService
方法接受这些枚举对象作为实参。例如,如需为 Google Ads API 的版本 V21
创建 CampaignServiceClient
的实例,您需要使用 Services.V21.CampaignService
作为实参来调用 GoogleAdsClient.GetService
方法,如上一个示例所示。
线程安全
在多个线程之间共享 GoogleAdsClient
实例是不安全的,因为在一个线程中对实例所做的配置更改可能会影响您在其他线程中创建的服务。从 GoogleAdsClient
实例获取新服务实例以及并行调用多个服务等操作是线程安全的。
多线程应用如下所示:
GoogleAdsClient client1 = new GoogleAdsClient();
GoogleAdsClient client2 = new GoogleAdsClient();
Thread userThread1 = new Thread(addAdGroups);
Thread userThread2 = new Thread(addAdGroups);
userThread1.start(client1);
userThread2.start(client2);
userThread1.join();
userThread2.join();
public void addAdGroups(object data) {
GoogleAdsClient client = (GoogleAdsClient) data;
// Do more operations here.
...
}
避免 .NET Framework 应用中出现冻结
同步方法可能会导致部分 .NET Framework 应用冻结。一个常见的示例是从 WinForm 应用的事件处理方法中进行 API 调用。
您可以通过以下两种方式解决此问题:
使用旧版 Grpc 库。
您可以设置 GoogleAdsConfig
的 UseGrpcCore
属性,以使用旧版 Grpc.Core
库,而不是默认的 Grpc.Net.Client
库。此方法尚未在 .NET Framework 应用上进行广泛测试,因此可能无法解决问题。以下是一个代码段示例:
GoogleAdsConfig config = new GoogleAdsConfig();
config.UseGrpcCore = true;
GoogleAdsClient client = new GoogleAdsClient(config);
使用异步方法。
您可以使用异步方法来避免冻结。下面是一些示例:
SearchStream
系统会调用 SearchStream()
,并将结果填充到列表视图中。
private async void button1_Click(object sender, EventArgs e)
{
// Get the GoogleAdsService.
GoogleAdsServiceClient googleAdsService = client.GetService(
Services.V21.GoogleAdsService);
// Create a query that will retrieve all campaigns.
string query = @"SELECT
campaign.id,
campaign.name,
campaign.network_settings.target_content_network
FROM campaign
ORDER BY campaign.id";
List items = new List();
Task t = googleAdsService.SearchStreamAsync(customerId.ToString(), query,
delegate (SearchGoogleAdsStreamResponse resp)
{
foreach (GoogleAdsRow googleAdsRow in resp.Results)
{
ListViewItem item = new ListViewItem();
item.Text = googleAdsRow.Campaign.Id.ToString();
item.SubItems.Add(googleAdsRow.Campaign.Name);
items.Add(item);
}
}
);
await t;
listView1.Items.AddRange(items.ToArray());
}
广告系列预算
系统会创建一个 CampaignBudget 调用,并使用 MessageBox
提醒显示新预算的资源名称。
private async void button2_Click(object sender, EventArgs e)
{
// Get the BudgetService.
CampaignBudgetServiceClient budgetService = client.GetService(
Services.V21.CampaignBudgetService);
// Create the campaign budget.
CampaignBudget budget = new CampaignBudget()
{
Name = "Interplanetary Cruise Budget #" + ExampleUtilities.GetRandomString(),
DeliveryMethod = BudgetDeliveryMethod.Standard,
AmountMicros = 500000
};
// Create the operation.
CampaignBudgetOperation budgetOperation = new CampaignBudgetOperation()
{
Create = budget
};
// Create the campaign budget.
Task t = budgetService.MutateCampaignBudgetsAsync(
customerId.ToString(), new CampaignBudgetOperation[] { budgetOperation });
await t;
MutateCampaignBudgetsResponse response = t.Result;
MessageBox.Show(response.Results[0].ResourceName);
}
错误处理
并非每次 API 调用都会成功。如果您的 API 调用因某种原因而失败,服务器可能会抛出错误。捕获 API 错误并对其进行适当处理非常重要。
发生 API 错误时,系统会抛出 GoogleAdsException
实例。其中包含详细信息,可帮助您找出问题所在:
// Get the CampaignService.
CampaignServiceClient campaignService = client.GetService(Services.V21.CampaignService);
// Create a campaign for update.
Campaign campaignToUpdate = new Campaign()
{
ResourceName = ResourceNames.Campaign(customerId, campaignId),
// More fields to update.
// ...
};
// Create the operation.
CampaignOperation operation = new CampaignOperation()
{
Update = campaignToUpdate,
UpdateMask = FieldMasks.AllSetFieldsOf(campaignToUpdate)
};
try
{
// Update the campaign.
MutateCampaignsResponse response = campaignService.MutateCampaigns(
customerId.ToString(), new CampaignOperation[] { operation });
// Display the results.
// ...
}
catch (GoogleAdsException e)
{
Console.WriteLine("Failure:");
Console.WriteLine($"Message: {e.Message}");
// Can examine to get more error details.
Console.WriteLine($"Failure: {e.Failure}");
// Can be shared with Google for further troubleshooting.
Console.WriteLine($"Request ID: {e.RequestId}");
}
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-26。
[null,null,["最后更新时间 (UTC):2025-08-26。"],[[["\u003cp\u003eThe Google Ads API client library for .NET will no longer support .NET 5.0 starting with version 19.0.0; upgrade to a newer .NET version before the end of 2024.\u003c/p\u003e\n"],["\u003cp\u003eInstall the client library using NuGet by adding a reference to the \u003ccode\u003eGoogle.Ads.GoogleAds\u003c/code\u003e package.\u003c/p\u003e\n"],["\u003cp\u003eAuthorize your API calls by providing client ID, client secret, refresh token, and developer token; guides are provided to obtain or generate these credentials.\u003c/p\u003e\n"],["\u003cp\u003eCreate a \u003ccode\u003eGoogleAdsClient\u003c/code\u003e instance and use its \u003ccode\u003eGetService\u003c/code\u003e method to create service classes for making API calls to various Google Ads services.\u003c/p\u003e\n"],["\u003cp\u003eHandle potential API errors by implementing error handling logic, catching \u003ccode\u003eGoogleAdsException\u003c/code\u003e to examine error details.\u003c/p\u003e\n"]]],[],null,["# Getting Started\n\nThis guide gives a brief overview of how to get started with the Google Ads API\n.NET library.\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\nInstallation\n------------\n\nThe client library binaries are distributed using NuGet. Add a NuGet reference\nto the [`Google.Ads.GoogleAds`\npackage](//www.nuget.org/packages/Google.Ads.GoogleAds/) in your project to use\nthe client library.\n\nSet up authorization\n--------------------\n\nTo authorize your API calls, you need to specify your client ID, client secret,\nrefresh token, and developer token to the library.\n\n### If you need to generate credentials\n\n- Follow the [Developer token guide](/google-ads/api/docs/get-started/dev-token) to obtain your developer token, if you don't already have one.\n- Follow the [OAuth desktop app flow](/google-ads/api/docs/client-libs/dotnet/oauth-desktop) guide to generate a client ID, client secret, and refresh token.\n\n### If you already have credentials\n\n- Copy the `GoogleAdsApi` node and the `GoogleAdsApi` section under the `configSections` node from the [`App.config` file in\n GitHub](https://github.com/googleads/google-ads-dotnet/blob/HEAD/Google.Ads.GoogleAds.Extensions/src/App.config) into your `App.config` / `Web.config` file. If you used NuGet to install the package, these nodes will be automatically inserted into your `App.config` / `Web.config` file.\n- Include the developer token, the client ID, client secret, and refresh token in your app's `App.config` / `Web.config`.\n\nThe [`App.config`](https://github.com/googleads/google-ads-dotnet/blob/HEAD/Google.Ads.GoogleAds.Extensions/src/App.config)\nfile included in GitHub is well-documented, but you can also refer to the\n[Configuration guide](/google-ads/api/docs/client-libs/dotnet/configuration)\nto learn more as well as use alternate ways to configure the client library,\nsuch as environment variables.\n\nMake an API call\n----------------\n\nThe basic usage of the client library is as follows: \n\n // Create a Google Ads client.\n GoogleAdsClient client = new GoogleAdsClient();\n\n // Create the required service.\n CampaignServiceClient campaignService =\n client.GetService(Services.V21.CampaignService);\n\n // Make more calls to service class.\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n### Create a GoogleAdsClient instance\n\nThe most important classes in the Google Ads API .NET library is the\n`GoogleAdsClient` class. It lets you create a pre-configured service class\nthat can be used for making API calls. `GoogleAdsClient` provides a default\nconstructor that creates a user object using the settings specified in your\napp's `App.config` / `Web.config`. Refer to the [Configuration\nguide](/google-ads/api/docs/client-libs/dotnet/configuration) for configuration\noptions. \n\n // Create a new GoogleAdsClient with the App.config settings.\n GoogleAdsClient user = new GoogleAdsClient();\n\n### Create a service\n\n`GoogleAdsClient` provides a `GetService` method that can be used to create an\nAds service. \n\n CampaignServiceClient campaignService = client.GetService(Services.V21.CampaignService);\n // Now make calls to CampaignService.\n\nWe provide a `Services` class that enumerates all the supported API versions and\nservices. The `GetService` method accepts these enumeration objects as argument\nwhen creating the service. For example, to create an instance of\n`CampaignServiceClient` for version `V21` of the Google Ads API,\nyou need to call `GoogleAdsClient.GetService` method with\n`Services.V21.CampaignService` as the argument, as shown\nin the previous example.\n\nThread safety\n-------------\n\nIt is not safe to share a `GoogleAdsClient` instance between multiple threads,\nsince the configuration changes you make on an instance in one thread might\naffect the services you create on other threads. Operations like obtaining\nnew service instances from a `GoogleAdsClient` instance and making calls to\nmultiple services in parallel are thread-safe.\n\nA multithreaded application would look something like this: \n\n GoogleAdsClient client1 = new GoogleAdsClient();\n GoogleAdsClient client2 = new GoogleAdsClient();\n\n Thread userThread1 = new Thread(addAdGroups);\n Thread userThread2 = new Thread(addAdGroups);\n\n userThread1.start(client1);\n userThread2.start(client2);\n\n userThread1.join();\n userThread2.join();\n\n public void addAdGroups(object data) {\n GoogleAdsClient client = (GoogleAdsClient) data;\n // Do more operations here.\n ...\n }\n\nAvoid freezes in .NET Framework applications\n--------------------------------------------\n\nSynchronous methods can cause some of your .NET Framework applications to\nfreeze. A common example is making API calls from an event handler method\nof a WinForm application.\n\nThere are two ways to address this issue:\n\n1. **Use the legacy Grpc library.**\n\n You can set the `UseGrpcCore` property of `GoogleAdsConfig` to use the\n legacy `Grpc.Core` library instead of the default `Grpc.Net.Client` library.\n This method has not been tested extensively on .NET Framework applications,\n so it might not solve the issue. Here is a sample snippet: \n\n GoogleAdsConfig config = new GoogleAdsConfig();\n config.UseGrpcCore = true;\n GoogleAdsClient client = new GoogleAdsClient(config);\n\n2. **Use asynchronous methods.**\n\n You can use asynchronous methods to avoid freezes. Here are some examples: \n\n ### SearchStream\n\n A call to `SearchStream()` is performed, and the results are\n populated into a list view. \n\n ```c#\n private async void button1_Click(object sender, EventArgs e)\n {\n // Get the GoogleAdsService.\n GoogleAdsServiceClient googleAdsService = client.GetService(\n Services.V21.GoogleAdsService);\n \n // Create a query that will retrieve all campaigns.\n string query = @\"SELECT\n campaign.id,\n campaign.name,\n campaign.network_settings.target_content_network\n FROM campaign\n ORDER BY campaign.id\";\n \n List items = new List();\n Task t = googleAdsService.SearchStreamAsync(customerId.ToString(), query,\n delegate (SearchGoogleAdsStreamResponse resp)\n {\n foreach (GoogleAdsRow googleAdsRow in resp.Results)\n {\n ListViewItem item = new ListViewItem();\n item.Text = googleAdsRow.Campaign.Id.ToString();\n item.SubItems.Add(googleAdsRow.Campaign.Name);\n items.Add(item);\n }\n }\n );\n await t;\n listView1.Items.AddRange(items.ToArray());\n }\n ```\n\n ### Campaign Budget\n\n A CampaignBudget call is created, and the resource name of the new budget is\n displayed using a `MessageBox` alert. \n\n ```c#\n private async void button2_Click(object sender, EventArgs e)\n {\n // Get the BudgetService.\n CampaignBudgetServiceClient budgetService = client.GetService(\n Services.V21.CampaignBudgetService);\n \n // Create the campaign budget.\n CampaignBudget budget = new CampaignBudget()\n {\n Name = \"Interplanetary Cruise Budget #\" + ExampleUtilities.GetRandomString(),\n DeliveryMethod = BudgetDeliveryMethod.Standard,\n AmountMicros = 500000\n };\n \n // Create the operation.\n CampaignBudgetOperation budgetOperation = new CampaignBudgetOperation()\n {\n Create = budget\n };\n \n // Create the campaign budget.\n Task t = budgetService.MutateCampaignBudgetsAsync(\n customerId.ToString(), new CampaignBudgetOperation[] { budgetOperation });\n \n await t;\n MutateCampaignBudgetsResponse response = t.Result;\n MessageBox.Show(response.Results[0].ResourceName);\n }\n ```\n\n \u003cbr /\u003e\n\nError handling\n--------------\n\nNot every API call will succeed. The server can throw errors if your API calls\nfail for some reason. It is important to capture API errors and handle them\nappropriately.\n\nA `GoogleAdsException` instance is thrown when an API error occurs. It has\ndetails to help you figure out what went wrong: \n\n // Get the CampaignService.\n CampaignServiceClient campaignService = client.GetService(Services.V21.CampaignService);\n\n // Create a campaign for update.\n Campaign campaignToUpdate = new Campaign()\n {\n ResourceName = ResourceNames.Campaign(customerId, campaignId),\n // More fields to update.\n // ...\n };\n\n // Create the operation.\n CampaignOperation operation = new CampaignOperation()\n {\n Update = campaignToUpdate,\n UpdateMask = FieldMasks.AllSetFieldsOf(campaignToUpdate)\n };\n\n try\n {\n // Update the campaign.\n MutateCampaignsResponse response = campaignService.MutateCampaigns(\n customerId.ToString(), new CampaignOperation[] { operation });\n\n // Display the results.\n // ...\n }\n catch (GoogleAdsException e)\n {\n Console.WriteLine(\"Failure:\");\n Console.WriteLine($\"Message: {e.Message}\");\n\n // Can examine to get more error details.\n Console.WriteLine($\"Failure: {e.Failure}\");\n\n // Can be shared with Google for further troubleshooting.\n Console.WriteLine($\"Request ID: {e.RequestId}\");\n }"]]