Integration of Bing search API in ASP.NET

Often we need to integrate search in public facing asp.net websites. The one option is to crawl the website ourselves, and collect the keyword/tokens and store them in database with urls. When user search for specific content, we can query the database and present them with search results.

Second option is to integrate Bing or Google search engines through their API. In this post we show how to integrate the Bing Search API in asp.net website. The prerequisites to use this code is to get Bing Application ID from their developers portal, which you can get from https://ssl.bing.com/webmaster/developers/appids.aspx

Once you have application id, it's easy to integrate bing search on your project. Place below code into your code behind file (.aspx.cs).

 

string url = "http://api.bing.net/xml.aspx?Appid={0}&sources={1}&query={2}&web.offset={3}&web.count={4}&Web.Options=DisableHostCollapsing+DisableQueryAlterations";
string completeUri = String.Format(url, "[ApplicationID]", "web", "BingSearch", 0, 10);
HttpWebRequest webRequest = null;
webRequest = (HttpWebRequest)WebRequest.Create(completeUri);
HttpWebResponse webResponse = null;
webResponse = (HttpWebResponse)webRequest.GetResponse();
XmlReader xmlReader = null;
xmlReader = XmlReader.Create(webResponse.GetResponseStream());
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(xmlReader);

string strTitle = "";
string strDescription = "";
string strUrl = "";
string searchResult = "";
foreach (XmlElement xe in xmldoc.GetElementsByTagName("web:WebResult"))
{


if (xe.GetElementsByTagName("web:Title").Count > 0)
    strTitle = xe.GetElementsByTagName("web:Title")[0].InnerText;
if (xe.GetElementsByTagName("web:Description").Count > 0)
    strDescription = xe.GetElementsByTagName("web:Description")[0].InnerText;
if (xe.GetElementsByTagName("web:Url").Count > 0)
    strUrl = xe.GetElementsByTagName("web:Url")[0].InnerText;

searchResult = searchResult + strTitle + "<br/>" + strDescription + "<br/>" + strUrl;
}

ltrlResult.Text = searchResult;

Please don't forget to replace [ApplicationID] with ID of the application which you have created on BING, and replace "BingSearch" with the keyword you want to search. Also you can see we've used different query string options in the Bing URL we are making HttpWebRequest, there are many more options you can use to customize your search results, you can find complete list of such options on http://msdn.microsoft.com/en-us/library/dd250845

Add comment

Loading