Quickstart: Use the Bing Custom Search .NET client library
Get started with the Bing Custom Search client library for C#. Follow these steps to install the package and try out the example code for basic tasks. The Bing Custom Search API enables you to create tailored, ad-free search experiences for topics that you care about. The source code for this sample can be found on GitHub.
Use the Bing Custom Search client library for C# to:
- Find search results on the web, from your Bing Custom Search instance.
Reference documentation | Library source code | Package (NuGet) | Samples
Prerequisites
- A Bing Custom Search instance. See Quickstart: Create your first Bing Custom Search instance for more information.
- Microsoft .NET Core.
- Any edition of Visual Studio 2017 or later.
- If you are using Linux/MacOS, this application can be run using Mono.
- The Bing Custom Search NuGet package.
- From Solution Explorer in Visual Studio, right-click your project and select Manage NuGet Packages from the menu. Install the
Microsoft.Azure.CognitiveServices.Search.CustomSearch
package. Installing the NuGet Custom Search package also installs the following assemblies:- Microsoft.Rest.ClientRuntime
- Microsoft.Rest.ClientRuntime.Azure
- Newtonsoft.Json
- From Solution Explorer in Visual Studio, right-click your project and select Manage NuGet Packages from the menu. Install the
Create and initialize the application
Create a new C# console application in Visual Studio. Then add the following packages to your project:
using System; using System.Linq; using Microsoft.Azure.CognitiveServices.Search.CustomSearch;
In the main method of your application, instantiate the search client with your API key.
var client = new CustomSearchAPI(new ApiKeyServiceClientCredentials("YOUR-SUBSCRIPTION-KEY"));
Send the search request and receive a response
Send a search query using your client's
SearchAsync()
method, and then save the response. Be sure to replace yourYOUR-CUSTOM-CONFIG-ID
with your instance's configuration ID (you can find the ID in the Bing Custom Search portal). This example searches for "Xbox":// This will look up a single query (Xbox). var webData = client.CustomInstance.SearchAsync(query: "Xbox", customConfig: Int32.Parse("YOUR-CUSTOM-CONFIG-ID")).Result;
The
SearchAsync()
method returns aWebData
object. Use the object to iterate through anyWebPages
that were found. This code finds the first webpage result and prints the webpage'sName
andURL
.if (webData?.WebPages?.Value?.Count > 0) { // find the first web page var firstWebPagesResult = webData.WebPages.Value.FirstOrDefault(); if (firstWebPagesResult != null) { Console.WriteLine("Number of webpage results {0}", webData.WebPages.Value.Count); Console.WriteLine("First web page name: {0} ", firstWebPagesResult.Name); Console.WriteLine("First web page URL: {0} ", firstWebPagesResult.Url); } else { Console.WriteLine("Couldn't find web results!"); } } else { Console.WriteLine("Didn't see any Web data.."); }