快速入门:使用 C# 将搜索请求发送到必应实体搜索 REST API

警告

2020 年 10 月 30 日,必应搜索 API 从 Azure AI 服务迁移到必应搜索服务。 本文档仅供参考。 有关更新的文档,请参阅 必应搜索 API 文档。 有关为必应搜索创建新 Azure 资源的说明,请参阅 通过 Azure 市场创建必应搜索资源。

使用此快速入门来进行第一次调用必应实体搜索 API,并查看 JSON 响应。 这个简单的 C# 应用程序将新闻搜索查询发送到 API,并显示响应。 GitHub上提供了此应用程序的源代码。

尽管此应用程序是用 C# 编写的,但 API 是一种 RESTful Web 服务,与大多数编程语言兼容。

先决条件

创建 Azure 资源

通过创建以下 Azure 资源之一来开始使用 Bing 实体搜索 API。

必应实体搜索资源

多服务资源

  • 可通过 Azure 门户使用,直到删除资源。
  • 跨多个 Azure AI 服务对应用程序使用相同的密钥和终结点。

创建和初始化项目

  1. 在 Visual Studio 中创建新的 C# 控制台解决方案。

  2. 添加 Newtonsoft.Json NuGet 包。

    1. 在解决方案资源管理器 中右键单击项目。
    2. 选择“管理 NuGet 包”。
    3. 搜索并选择 Newtonsoft.Json,然后安装包。
  3. 然后,将以下命名空间添加到主代码文件中:

    using Newtonsoft.Json;
    using System;
    using System.Net.Http;
    using System.Text;
    
  4. 创建新类,并为 API 终结点、订阅密钥和要搜索的查询添加变量。 可以在以下代码中使用全局终结点,也可以使用 Azure 门户中为资源显示的 自定义子域 终结点。

    namespace EntitySearchSample
    {
        class Program
        {
            static string host = "https://api.bing.microsoft.com";
            static string path = "/v7.0/search";
    
            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 响应

  1. 在该类中,创建一个名为 Search()的函数。 在此函数中,创建新的 HttpClient 对象,并将订阅密钥添加到 Ocp-Apim-Subscription-Key 标头。

  2. 通过组合主机和路径来构造请求的 URI。 然后,添加您的市场,并对您的查询进行 URL 编码。

  3. 异步等待 client.GetAsync() 以获取 HTTP 响应,然后通过等待 ReadAsStringAsync()来存储 JSON 响应。

  4. 使用 JsonConvert.DeserializeObject() 设置 JSON 字符串的格式,并将其打印到控制台。

    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);
    }
    
  5. 在应用程序的 Main() 方法中,调用 Search() 函数。

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

示例 JSON 响应

成功的响应在 JSON 中返回,如以下示例所示:

{
  "_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"
      },
      
      . . .
    ]
  }
}

后续步骤