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

警告

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

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

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

先决条件

创建 Azure 资源

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

必应实体搜索资源

  • 在删除资源前,可通过 Azure 门户使用。
  • 使用免费定价层试用该服务,稍后升级到用于生产的付费层。
  • 必应实体搜索也在必应搜索 v7 资源的付费层中提供。

多服务资源

  • 在删除资源前,可通过 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"
      },
      
      . . .
    ]
  }
}

后续步骤