開始使用
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
本指南簡要說明如何開始使用 Google Ads API .NET 程式庫。
安裝
用戶端程式庫二進位檔是透過 NuGet 發行。在專案的 Google.Ads.GoogleAds
package 中新增 NuGet 參照,即可使用用戶端程式庫。
設定授權
如要授權 API 呼叫,您需要向程式庫指定用戶端 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
方法,可用於建立 Google Ads 服務。
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}");
}
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2025-08-26 (世界標準時間)。
[null,null,["上次更新時間: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 }"]]