快速入門:使用 C# 將搜尋要求傳送至 Bing 實體搜尋 REST APIQuickstart: Send a search request to the Bing Entity Search REST API using C#

使用本快速入門以第一次呼叫 Bing 實體搜尋 API,並檢視 JSON 回應。Use this quickstart to make your first call to the Bing Entity Search API and view the JSON response. 這個簡單的 C# 應用程式會將新聞搜尋查詢傳送給 API,並顯示回應。This simple C# application sends a news search query to the API, and displays the response. 您可以在 GitHub 上找到此應用程式的原始程式碼。The source code for this application is available on GitHub.

雖然此應用程式是以 C# 撰寫的,但 API 是一種與大多數程式設計語言都相容的 RESTful Web 服務。While this application is written in C#, the API is a RESTful Web service compatible with most programming languages.

PrerequisitesPrerequisites

  • Visual Studio 2017 或更新版本的任何版本。Any edition of Visual Studio 2017 or later.

  • Json.NET 架構 (以 NuGet 套件形式提供)。The Json.NET framework, available as a NuGet package. 在 Visual Studio 中安裝 NuGet 套件:To install the NuGet package in Visual Studio:

    1. 在 [方案總管] 中,以滑鼠右鍵按一下您的專案。Right click your project in Solution Explorer.
    2. 選取 [管理 NuGet 套件] 。Select Manage NuGet Packages.
    3. 搜尋 Newtonsoft.Json 並安裝套件Search for Newtonsoft.Json and install the package.
  • 如果您使用 Linux/MacOS,則可以使用 Mono 來執行此應用程式。If you're using Linux/MacOS, this application can be run by using Mono.

建立 Azure 資源Create an Azure resource

藉由建立下列其中一項 Azure 資源,開始使用 Bing 實體搜尋 API。Start using the Bing Entity Search API by creating one of the Azure resources below.

  • 建立試用資源Create a trial resource:

    • 不需要 Azure 訂用帳戶。No Azure subscription needed.
    • 可免費使用 7 天。Valid for seven days, for free. 註冊之後,即可在 Azure 網站上取得試用金鑰與端點。After signing up, a trial key and endpoint will be available on the Azure website.
  • 建立 Bing 實體搜尋資源Create a Bing Entity Search resource:

    • 您可以透過 Azure 入口網站取得該資源,直到將其刪除為止。Available through the Azure portal until you delete the resource.
    • 使用免費定價層來試用服務,之後可升級至付費層以用於實際執行環境。Use the free pricing tier to try the service, and upgrade later to a paid tier for production.
    • Bing 實體搜尋也會在 Bing 搜尋 v7 資源的付費層中提供。Bing Entity Search is also offered in paid tiers of the Bing Search v7 resource.
  • 建立多服務資源Create a Multi-Service resource:

    • 您可以透過 Azure 入口網站取得該資源,直到將其刪除為止。Available through the Azure portal until you delete the resource.
    • 針對您的應用程式,跨多個認知服務使用相同的金鑰和端點。Use the same key and endpoint for your applications, across multiple Cognitive Services.

建立專案並將其初始化Create and initialize a project

  1. 在 Visual Studio 中建立新的 C# 主控台解決方案。create a new C# console solution in Visual Studio. 然後將下列命名空間新增至主要程式碼檔案。Then add the following namespaces into the main code file.

    using Newtonsoft.Json;
    using System;
    using System.Net.Http;
    using System.Text;
    
  2. 建立新的類別,然後新增 API 端點變數、您的訂用帳戶金鑰和您想要搜尋的查詢。Create a new class, and add variables for the API endpoint, your subscription key, and query you want to search. 您可以使用下方的全域端點,也可以使用 Azure 入口網站中針對您的資源所顯示的自訂子網域端點。You can use the global endpoint below, or the custom subdomain endpoint displayed in the Azure portal for your resource.

    namespace EntitySearchSample
    {
        class Program
        {
            static string host = "https://api.cognitive.microsoft.com";
            static string path = "/bing/v7.0/entities";
    
            static string market = "en-US";
    
            // NOTE: Replace this example key with a valid subscription key.
            static string key = "ENTER YOUR KEY HERE";
    
            static string query = "italian restaurant near me";
        //...
        }
    }
    

傳送要求並取得 API 回應Send a request and get the API response

  1. 在該類別內建立稱為 Search() 的函式。Within the class, create a function called Search(). 建立新的 HttpClient 物件,並將您的訂用帳戶金鑰新增至 Ocp-Apim-Subscription-Key 標頭。Create a new HttpClient object, and add your subscription key to the Ocp-Apim-Subscription-Key header.

    1. 藉由結合主機和路徑,來建構要求的 URI。Construct the URI for your request by combining the host and path. 然後新增您的市場,並為查詢進行 URL 編碼。Then add your market, and URL-encode your query.

    2. 等待 client.GetAsync() 取得 HTTP 回應,然後藉由等待 ReadAsStringAsync() 來儲存 json 回應。Await client.GetAsync() to get a HTTP response, and then store the json response by awaiting ReadAsStringAsync().

    3. JsonConvert.DeserializeObject() 格式化 JSON 字串,並將其列印到主控台。Format the JSON string with JsonConvert.DeserializeObject() and print it to the console.

      async static void Search()
      {
       //...
       HttpClient client = new HttpClient();
       client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", key);
      
       string uri = host + path + "?mkt=" + market + "&q=" + System.Net.WebUtility.UrlEncode(query);
      
       HttpResponseMessage response = await client.GetAsync(uri);
      
       string contentString = await response.Content.ReadAsStringAsync();
       dynamic parsedJson = JsonConvert.DeserializeObject(contentString);
       Console.WriteLine(parsedJson);
      }
      
  2. 在應用程式的 Main 方法中,呼叫 Search() 函式。In the main method of your application, call the Search() function.

    static void Main(string[] args)
    {
        Search();
        Console.ReadLine();
    }
    

範例 JSON 回應Example JSON response

如以下範例所示,成功的回應會以 JSON 格式來傳回:A successful response is returned in JSON, as shown in the following example:

{
  "_type": "SearchResponse",
  "queryContext": {
    "originalQuery": "italian restaurant near me",
    "askUserForLocation": true
  },
  "places": {
    "value": [
      {
        "_type": "LocalBusiness",
        "webSearchUrl": "https://www.bing.com/search?q=sinful+bakery&filters=local...",
        "name": "Liberty's Delightful Sinful Bakery & Cafe",
        "url": "https://www.contoso.com/",
        "entityPresentationInfo": {
          "entityScenario": "ListItem",
          "entityTypeHints": [
            "Place",
            "LocalBusiness"
          ]
        },
        "address": {
          "addressLocality": "Seattle",
          "addressRegion": "WA",
          "postalCode": "98112",
          "addressCountry": "US",
          "neighborhood": "Madison Park"
        },
        "telephone": "(800) 555-1212"
      },

      . . .
      {
        "_type": "Restaurant",
        "webSearchUrl": "https://www.bing.com/search?q=Pickles+and+Preserves...",
        "name": "Munson's Pickles and Preserves Farm",
        "url": "https://www.princi.com/",
        "entityPresentationInfo": {
          "entityScenario": "ListItem",
          "entityTypeHints": [
            "Place",
            "LocalBusiness",
            "Restaurant"
          ]
        },
        "address": {
          "addressLocality": "Seattle",
          "addressRegion": "WA",
          "postalCode": "98101",
          "addressCountry": "US",
          "neighborhood": "Capitol Hill"
        },
        "telephone": "(800) 555-1212"
      },
      
      . . .
    ]
  }
}

後續步驟Next steps