Bing Search in C#: A step by step walk-through tutorial


This blog is the 3rd article of the series Search in C# example demonstration. If you are interested in my earlier blogs in this series, please refer to below blogs:

In this blog, I am going to walk through how to do Bing Web Search using the latest v5 API.

BingSearch

The basic idea can be demonstrated using the below code, as shown in Microsoft’s v5 API documentation here.

static async void MakeRequest()
{
    var client = new HttpClient();
    var queryString = HttpUtility.ParseQueryString(string.Empty);
    client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "{subscription key}");
    queryString["Category"] = "{string}";
    var uri = "https://api.cognitive.microsoft.com/bing/v5.0/news/?" + queryString;
    var response = await client.GetAsync(uri);
}

Here an important part of the code is the  Ocp-Apim-Subscription-Key, where you can get it from below instructions:

Get a Subscription Key

Bing uses a subscription key to control access to the Bing family of APIs. To get your key, go to Getting started for free and click Let’s go which will walk you through the steps of getting a key.

Once you have created the key, it will be something like below:

image

 

Calling the above function will give you the raw json string, here is the example RankingResponse.

image

To deserialize this raw json string to Plain Old CLR Objects (POCO) , you can do this in a handy way:

In VisualStudio 2005, click menu Edit > Paste Special > Paste JSON As Classes

as shown in below snapshot:

image 

This way, all the required classes are automatically generated for you.

In this blog, I am using NewtonSoft library (Json.Net) to get the response POCO objects.The example usage of this code is as follows:

image
The full source code project is hosted at GitHub here. Star it if you like!

One thought on “Bing Search in C#: A step by step walk-through tutorial

  1. Pingback: Bing Search in C#: A step by step walk-through tutorial - How to Code .NET

Leave a comment