快速入門:使用 Bing Web 搜尋 REST API 和 C# 來搜尋 WebQuickstart: Search the web using the Bing Web Search REST API and C#

使用本快速入門進行對 Bing Web 搜尋 API 第一次的呼叫,並接收 JSON 回應。Use this quickstart to make your first call to the Bing Web Search API and receive the JSON response. 這個 C# 應用程式會將搜尋要求傳送給 API,並顯示回應。This C# application sends a search request to the API, and shows the response. 雖然此應用程式是以 C# 撰寫的,但 API 是一種與大多數程式設計語言都相容的 RESTful Web 服務。While this application is written in C#, the API is a RESTful Web service compatible with most programming languages.

必要條件Prerequisites

以下是執行本快速入門之前的幾個必備項目:Here are a few things that you'll need before running this quickstart:

這個範例程式只使用 .NET Core 類別。This example program only uses .NET Core classes.

本快速入門需要 Azure 認知服務帳戶及 Bing 搜尋 API。This quickstart requires an Azure Cognitive Services account with Bing Search APIs. 如果您還沒有帳戶,可以使用免費試用來取得訂用帳戶金鑰。If you don't have an account, you can use the free trial to get a subscription key.

建立專案並宣告相依性Create a project and declare dependencies

在 Visual Studio 或 Mono 中建立新專案。Create a new project in Visual Studio or Mono. 然後使用此程式碼匯入必要的命名空間和類型。Then use this code to import required namespaces and types.

using System;
using System.Text;
using System.Net;
using System.IO;
using System.Collections.Generic;

為您的程式宣告命名空間和類別Declare a namespace and class for your program

在本快速入門中,我們將大部分程式碼放在 Program 類別中。In this quickstart, we'll put most of the code in the Program class. 首先,在專案中建立 BingSearchApiQuickstart 命名空間和 Program 類別。Start by creating the BingSearchApiQuickstart namespace and Program class in your project.

namespace BingSearchApisQuickstart
{
    class Program
    {
        // The code in the following sections goes here.
    }
}

定義變數Define variables

必須先設定幾個變數才能繼續。A few variables must be set before we can continue. 請確認 uriBase 有效,並將 accessKey 值換成您的 Azure 帳戶中有效的訂用帳戶金鑰。Confirm that the uriBase is valid and replace the accessKey value with a valid subscription key from your Azure account. 請自行取代 searchTerm 的值來自訂搜尋查詢。Feel free to customize the search query by replacing the value for searchTerm. 請記得將此程式碼新增至 Program 類別,如先前所述。Remember to add this code to the Program class as noted above.

// Enter a valid subscription key.
const string accessKey = "enter key here";
/*
 * If you encounter unexpected authorization errors, double-check this value
 * against the endpoint for your Bing Web search instance in your Azure
 * dashboard.
 */
const string uriBase = "https://api.cognitive.microsoft.com/bing/v7.0/search";
const string searchTerm = "Microsoft Cognitive Services";

宣告 Main 方法Declare the Main method

Main() 是必要方法,也是程式啟動時叫用的第一個方法。The Main() method is required and it's the first method invoked when the program is started. 在此應用程式中,main 方法會驗證 accessKey、提出要求及列印回應。In this application, the main method validates the accessKey, makes a request, and prints the response.

請記住,main() 取決於接下來幾節所建立的方法。Keep in mind that main() is dependent on methods that are created in the next few sections.

static void Main()
{
    Console.OutputEncoding = System.Text.Encoding.UTF8;
    if (accessKey.Length == 32)
    {
        Console.WriteLine("Searching the Web for: " + searchTerm);
        SearchResult result = BingWebSearch(searchTerm);
        Console.WriteLine("\nRelevant HTTP Headers:\n");
        foreach (var header in result.relevantHeaders)
            Console.WriteLine(header.Key + ": " + header.Value);

        Console.WriteLine("\nJSON Response:\n");
        Console.WriteLine(JsonPrettyPrint(result.jsonResult));
    }
    else
    {
        Console.WriteLine("Invalid Bing Search API subscription key!");
        Console.WriteLine("Please paste yours into the source code.");
    }
    Console.Write("\nPress Enter to exit ");
    Console.ReadLine();
}

建立搜尋結果的結構Create a struct for search results

此結構會傳回具有相關標題的搜尋結果。This struct returns search results with relevant headers. 對 Bing Web 搜尋 API 提出要求時,會呼叫此結構來建立結果物件。It's called when making a request to the Bing Web Search API to create a result object.

// Returns search results with headers.
struct SearchResult
{
    public String jsonResult;
    public Dictionary<String, String> relevantHeaders;
}

建構要求Construct a request

使用此程式碼來建構搜尋查詢、執行 GET 要求及處理回應。Use this code to construct the search query, perform the GET request, and handle the response.

/// <summary>
/// Makes a request to the Bing Web Search API and returns data as a SearchResult.
/// </summary>
static SearchResult BingWebSearch(string searchQuery)
{
    // Construct the search request URI.
    var uriQuery = uriBase + "?q=" + Uri.EscapeDataString(searchQuery);

    // Perform request and get a response.
    WebRequest request = HttpWebRequest.Create(uriQuery);
    request.Headers["Ocp-Apim-Subscription-Key"] = accessKey;
    HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result;
    string json = new StreamReader(response.GetResponseStream()).ReadToEnd();

    // Create a result object.
    var searchResult = new SearchResult()
    {
        jsonResult = json,
        relevantHeaders = new Dictionary<String, String>()
    };

    // Extract Bing HTTP headers.
    foreach (String header in response.Headers)
    {
        if (header.StartsWith("BingAPIs-") || header.StartsWith("X-MSEdge-"))
            searchResult.relevantHeaders[header] = response.Headers[header];
    }
    return searchResult;
}

將回應格式化Format the response

這個方法會格式化 JSON 回應,主要是縮排並新增分行符號。This method formats the JSON response, primarily indenting and adding line breaks.

/// <summary>
/// Formats the JSON string by adding line breaks and indents.
/// </summary>
/// <param name="json">The raw JSON string.</param>
/// <returns>The formatted JSON string.</returns>
static string JsonPrettyPrint(string json)
{
    if (string.IsNullOrEmpty(json))
        return string.Empty;

    json = json.Replace(Environment.NewLine, "").Replace("\t", "");

    StringBuilder sb = new StringBuilder();
    bool quote = false;
    bool ignore = false;
    char last = ' ';
    int offset = 0;
    int indentLength = 2;

    foreach (char ch in json)
    {
        switch (ch)
        {
            case '"':
                if (!ignore) quote = !quote;
                break;
            case '\\':
                if (quote && last != '\\') ignore = true;
                break;
        }

        if (quote)
        {
            sb.Append(ch);
            if (last == '\\' && ignore) ignore = false;
        }
        else
        {
            switch (ch)
            {
                case '{':
                    case '[':
                        sb.Append(ch);
                        sb.Append(Environment.NewLine);
                        sb.Append(new string(' ', ++offset * indentLength));
                        break;
                    case ']':
                    case '}':
                        sb.Append(Environment.NewLine);
                        sb.Append(new string(' ', --offset * indentLength));
                        sb.Append(ch);
                        break;
                    case ',':
                        sb.Append(ch);
                        sb.Append(Environment.NewLine);
                        sb.Append(new string(' ', offset * indentLength));
                        break;
                    case ':':
                        sb.Append(ch);
                        sb.Append(' ');
                        break;
                    default:
                        if (quote || ch != ' ') sb.Append(ch);
                        break;
            }
        }
        last = ch;
    }
    return sb.ToString().Trim();
}

組合在一起Put it all together

最後一步就是執行您的程式碼!The last step is to run your code! 如果想要將您的程式碼與我們的程式碼做比較,GitHub 上提供程式碼範例 (英文)。If you'd like to compare your code with ours, sample code is available on GitHub.

範例回應Sample response

來自 Bing Web 搜尋 API 的回應會以 JSON 格式傳回。Responses from the Bing Web Search API are returned as JSON. 本範例回應已截斷而只顯示單一結果。This sample response has been truncated to show a single result.

{
  "_type": "SearchResponse",
  "queryContext": {
    "originalQuery": "Microsoft Cognitive Services"
  },
  "webPages": {
    "webSearchUrl": "https://www.bing.com/search?q=Microsoft+cognitive+services",
    "totalEstimatedMatches": 22300000,
    "value": [
      {
        "id": "https://api.cognitive.microsoft.com/api/v7/#WebPages.0",
        "name": "Microsoft Cognitive Services",
        "url": "https://www.microsoft.com/cognitive-services",
        "displayUrl": "https://www.microsoft.com/cognitive-services",
        "snippet": "Knock down barriers between you and your ideas. Enable natural and contextual interaction with tools that augment users' experiences via the power of machine-based AI. Plug them in and bring your ideas to life.",
        "deepLinks": [
          {
            "name": "Face API",
            "url": "https://azure.microsoft.com/services/cognitive-services/face/",
            "snippet": "Add facial recognition to your applications to detect, identify, and verify faces using a Face API from Microsoft Azure. ... Cognitive Services; Face API;"
          },
          {
            "name": "Text Analytics",
            "url": "https://azure.microsoft.com/services/cognitive-services/text-analytics/",
            "snippet": "Cognitive Services; Text Analytics API; Text Analytics API . Detect sentiment, ... you agree that Microsoft may store it and use it to improve Microsoft services, ..."
          },
          {
            "name": "Computer Vision API",
            "url": "https://azure.microsoft.com/services/cognitive-services/computer-vision/",
            "snippet": "Extract the data you need from images using optical character recognition and image analytics with Computer Vision APIs from Microsoft Azure."
          },
          {
            "name": "Emotion",
            "url": "https://www.microsoft.com/cognitive-services/en-us/emotion-api",
            "snippet": "Cognitive Services Emotion API - microsoft.com"
          },
          {
            "name": "Bing Speech API",
            "url": "https://azure.microsoft.com/services/cognitive-services/speech/",
            "snippet": "Add speech recognition to your applications, including text to speech, with a speech API from Microsoft Azure. ... Cognitive Services; Bing Speech API;"
          },
          {
            "name": "Get Started for Free",
            "url": "https://azure.microsoft.com/services/cognitive-services/",
            "snippet": "Add vision, speech, language, and knowledge capabilities to your applications using intelligence APIs and SDKs from Cognitive Services."
          }
        ]
      }
    ]
  },
  "relatedSearches": {
    "id": "https://api.cognitive.microsoft.com/api/v7/#RelatedSearches",
    "value": [
      {
        "text": "microsoft bot framework",
        "displayText": "microsoft bot framework",
        "webSearchUrl": "https://www.bing.com/search?q=microsoft+bot+framework"
      },
      {
        "text": "microsoft cognitive services youtube",
        "displayText": "microsoft cognitive services youtube",
        "webSearchUrl": "https://www.bing.com/search?q=microsoft+cognitive+services+youtube"
      },
      {
        "text": "microsoft cognitive services search api",
        "displayText": "microsoft cognitive services search api",
        "webSearchUrl": "https://www.bing.com/search?q=microsoft+cognitive+services+search+api"
      },
      {
        "text": "microsoft cognitive services news",
        "displayText": "microsoft cognitive services news",
        "webSearchUrl": "https://www.bing.com/search?q=microsoft+cognitive+services+news"
      },
      {
        "text": "ms cognitive service",
        "displayText": "ms cognitive service",
        "webSearchUrl": "https://www.bing.com/search?q=ms+cognitive+service"
      },
      {
        "text": "microsoft cognitive services text analytics",
        "displayText": "microsoft cognitive services text analytics",
        "webSearchUrl": "https://www.bing.com/search?q=microsoft+cognitive+services+text+analytics"
      },
      {
        "text": "microsoft cognitive services toolkit",
        "displayText": "microsoft cognitive services toolkit",
        "webSearchUrl": "https://www.bing.com/search?q=microsoft+cognitive+services+toolkit"
      },
      {
        "text": "microsoft cognitive services api",
        "displayText": "microsoft cognitive services api",
        "webSearchUrl": "https://www.bing.com/search?q=microsoft+cognitive+services+api"
      }
    ]
  },
  "rankingResponse": {
    "mainline": {
      "items": [
        {
          "answerType": "WebPages",
          "resultIndex": 0,
          "value": {
            "id": "https://api.cognitive.microsoft.com/api/v7/#WebPages.0"
          }
        }
      ]
    },
    "sidebar": {
      "items": [
        {
          "answerType": "RelatedSearches",
          "value": {
            "id": "https://api.cognitive.microsoft.com/api/v7/#RelatedSearches"
          }
        }
      ]
    }
  }
}

後續步驟Next steps

另請參閱See also