网站导航网学 原创论文 原创专题 网站设计 最新系统 原创论文 论文降重 发表论文 论文发表 UI设计定制 论文答辩PPT格式排版 期刊发表 论文专题
返回网学首页
网学原创论文
最新论文 推荐专题 热门论文 论文专题
当前位置: 网学 > 设计资源 > .Net编程 > 正文

在ASP.NETWebApplication中通过SOAP协议调用Bing搜索服务【附示例下载】

论文降重修改服务、格式排版等 获取论文 论文降重及排版 论文发表 相关服务

本文介绍了如何在ASP.NET Web Application中将Bing搜索作为Web Service来使用,并通过HTTP的SOAP协议在ASP.NET Web Application中调用Bing搜索功能。当然,我们也可以使用XML和JSON来调用Bing搜索服务,稍后会给出一些相关的例子。

  本文中我将向大家演示下面这些内容:【示例代码下载】

  • 创建一个Web Application与Bing搜索服务进行交互
  • 添加Bing搜索服务的引用
  • 使用Bing SourceTypes演示在线搜索功能

Bing搜索服务介绍

  将Bing搜索功能作为Web Service来使用可以在我们的应用程序中简化许多较为复杂的功能,如创建索引、建立相关逻辑、解决数据存储等问题,本文旨从在你的应用程序中添加Bing Web Service开始。

  什么是Web Service,想必大家都已经比较清楚了,它是Web Server上的一个程序组件,能够被客户端应用程序通过HTTP协议在Web上进行调用。有关Web Service的详细介绍,你可以查看MSDN上的文章Using ASP.NET Web Serices.

  使用Bing搜索服务你可以在你的程序中集成下列功能:

  • 从Internet上获取有用的信息
  • 在你的应用程序中添加广告内容
  • 提高和增强搜索功能
  • 查找特定位置信息
  • 翻译条款和文本块

  你可以通过Bing API来调用Bing Service的各种功能。上面提到的这些功能都或多或少地使用到了Bing API SourceTypes。一个SourceType是一个可以通过Bing API进行访问的信息源,有关所有这些SourceTypes的描述可以访问MSDN:About the Bing API。

先决条件

  要完成本文中提到的这些功能,你必须具备下面这些条件:

  • Visual Studio 2010(稍低版本的VS也可以,如Visual Studio 2008)
  • 能够通过SOAP协议(1.1)和HTTP协议(1.1)向服务器端发送请求
  • 能够解析SOAP和XML

创建Web Application

  现在我们开始展示如何创建一个Web Application并使用Bing搜索服务。

首先打开Visual Studio并创建一个普通的Web Application工程。如果你使用的是Visual Studio 2010,建议创建ASP.NET Empty Web Application类型的工程。  2010-7-19 14-57-43  然后我们需要在工程中添加Bing Search Service的Web引用。我们通过Web Service发现程序以获得Web服务的位置和描述信息,在Visual Studio中,Web Service发现程序是一个WSDL(Web Services Description Language)格式的XML文件,用来从Web站点中找到Web服务的描述信息。当我们在工程中添加Web引用时,Visual Studio会生成一个代理类,用来提供Web服务的本地描述,从而允许客户端代码可以直接调用Web Service提供的功能。你可以通过代理类来调用Web Service提供的方法,代理类会负责在客户端应用程序和Web Service之间进行通信。下面是在Visual Studio中添加Web引用到Web Application的步骤:

  打开Solution Explorer,右键点击项目名称,在弹出的上下文菜单中选择Add Web Reference。

2010-7-19 14-47-46

  在弹出的对话框中输入/uploadfile/201101/20/05195438410.png" title="2010-7-19 14-59-15" />   如果连接成功,你应该会看到有一个服务“search”被找到,点击Add Rederence按钮添加该Web引用到工程中。

  浏览Solution Explorer面板,你会发现多了一个Web Reference文件夹,里面有live search service的API,双击它可以在Object Browser窗口中查看命名空间和对象。

  同时,Web.config文件也会被修改,其中包含了soap.asmx服务的引用地址,如:

  1. <applicationSettings>  
  2.     <BingSearchDemo.Properties.Settings>  
  3.         <setting name="BingSearchDemo_net_live_search_api_LiveSearchService"  
  4.             serializeAs="String">  
  5.             <value>http://api.search.live.net:80/soap.asmx</value>  
  6.         </setting>  
  7.     </BingSearchDemo.Properties.Settings>  
  8. </applicationSettings> 

使用Bing ServiceTypes进行搜索  

我们可以选择不同的Bing ServiceType进行在线搜索,下面是两种比较简单的应用类型:

Web:从Internet获取信息。

Phonebook:查找特定位置信息。
  如何选择ServiceType呢?在BingSearchDemo.net.live.search.api命名空间下可以找到SourceType枚举对象,它下面包含了所有可能的SourceType枚举类型,如Ad、Image、InstantAnswer、MoibleWeb、News、Phonebook、QueryLocation、RelatedSearch、Showtimes、Spell、Translation、Video、Weather、Web、XRank。下面有两个类,分别使用SourceType.Web类型和SourceType.Phonebook类型:

UsingWebCourceType

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Xml;  
  6. using BingSearchDemo.net.live.search.api;  
  7.  
  8. namespace BingSearchDemo  
  9. {  
  10.     public class UsingWebSourceType  
  11.     {  
  12.         // Replace the following string with the AppId you received from the  
  13.         // Bing Developer Center.  
  14.         const string AppId = "0C6C67B56FCE6E3C401882E9A7BAE196062FF144";  
  15.  
  16.         public static SearchResponse PerformLiveSearch()  
  17.         {  
  18.             // LiveSearchService implements IDisposable.  
  19.             using (LiveSearchService service = new LiveSearchService())  
  20.             {  
  21.                 SearchResponse response = new SearchResponse();  
  22.                 try  
  23.                 {  
  24.                     SearchRequest request = BuildRequest();  
  25.                     // Send the request; display the response.  
  26.                     response = service.Search(request);  
  27.                 }  
  28.                 catch (System.Web.Services.Protocols.SoapException ex)  
  29.                 {  
  30.                     // A SOAP Exception was thrown. Display error details.  
  31.                     DisplayErrors(ex.Detail);  
  32.                 }  
  33.                 catch (System.Net.WebException ex)  
  34.                 {  
  35.                     // An exception occurred while accessing the network.  
  36.                     HttpContext.Current.Response.Write(ex.Message);  
  37.                 }  
  38.                 return response;  
  39.             }  
  40.         }  
  41.  
  42.         public static SearchRequest BuildRequest()  
  43.         {  
  44.             SearchRequest request = new SearchRequest();  
  45.             // Common request fields (required)  
  46.             request.AppId = AppId;  
  47.             request.Query = "msdn blogs";  
  48.             request.Sources = new SourceType { SourceType.Web };  
  49.             // Common request fields (optional)  
  50.             request.Version = "2.0";  
  51.             request.Market = "en-us";  
  52.             request.Adult = AdultOption.Moderate;  
  53.             request.AdultSpecified = true;  
  54.             request.Options = new SearchOption { SearchOption.EnableHighlighting };  
  55.             // Web-specific request fields (optional)  
  56.             request.Web = new WebRequest();  
  57.             request.Web.Count = 10;  
  58.             request.Web.CountSpecified = true;  
  59.             request.Web.Offset = 0;  
  60.             request.Web.OffsetSpecified = true;  
  61.             request.Web.Options = new WebSearchOption { WebSearchOption.DisableHostCollapsing, WebSearchOption.DisableQueryAlterations };  
  62.             return request;  
  63.         }  
  64.  
  65.         static void DisplayErrors(XmlNode errorDetails)  
  66.         {  
  67.             // Add the default namespace to the namespace manager.  
  68.             XmlNamespaceManager nsmgr = new XmlNamespaceManager(errorDetails.OwnerDocument.NameTable);  
  69.             nsmgr.AddNamespace("api""http://schemas.microsoft.com/LiveSearch/2008/03/Search"); XmlNodeList errors = errorDetails.SelectNodes("./api:Errors/api:Error", nsmgr);  
  70.               
  71.             if (errors != null)  
  72.             {  
  73.                 // Iterate over the list of errors and display error details.  
  74.                 HttpContext.Current.Response.Write("Errors");  
  75.                 foreach (XmlNode error in errors)  
  76.                 {  
  77.                     foreach (XmlNode detail in error.ChildNodes)  
  78.                     {  
  79.                         HttpContext.Current.Response.Write(detail.Name + ": " + detail.InnerText);  
  80.                     }  
  81.                 }  
  82.             }  
  83.         }  
  84.     }  

UsingPhonebookSourceType

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using BingSearchDemo.net.live.search.api;  
  6. using System.Xml;  
  7.  
  8. namespace BingSearchDemo  
  9. {  
  10.     public class UsingPhonebookSourceType  
  11.     {  
  12.         // Replace the following string with the AppId you received from the  
  13.         // Bing Developer Center.  
  14.         const string AppId = "0C6C67B56FCE6E3C401882E9A7BAE196062FF144";  
  15.  
  16.         public static SearchResponse PerformLiveSearch()  
  17.         {  
  18.             // LiveSearchService implements IDisposable.  
  19.             using (LiveSearchService service = new LiveSearchService())  
  20.             {  
  21.                 SearchResponse response = new SearchResponse();  
  22.                 try  
  23.                 {  
  24.                     SearchRequest request = BuildRequest();  
  25.                     // Send the request; display the response.  
  26.                     response = service.Search(request);  
  27.                 }  
  28.                 catch (System.Web.Services.Protocols.SoapException ex)  
  29.                 {  
  30.                     // A SOAP Exception was thrown. Display error details.  
  31.                     DisplayErrors(ex.Detail);  
  32.                 }  
  33.                 catch (System.Net.WebException ex)  
  34.                 {  
  35.                     // An exception occurred while accessing the network.  
  36.                     HttpContext.Current.Response.Write(ex.Message);  
  37.                 }  
  38.                 return response;  
  39.             }  
  40.         }  
  41.  
  42.         public static SearchRequest BuildRequest()  
  43.         {  
  44.             SearchRequest request = new SearchRequest();  
  45.  
  46.             // Common request fields (required)  
  47.             request.AppId = AppId;  
  48.             request.Query = "microsoft offices";  
  49.             request.Sources = new SourceType { SourceType.Phonebook };  
  50.  
  51.             // Common request fields (optional)  
  52.             request.Version = "2.0";  
  53.             request.Market = "en-us";  
  54.             request.UILanguage = "en";  
  55.             request.Latitude = 47.603450;  
  56.             request.LatitudeSpecified = true;  
  57.             request.Longitude = -122.329696;  
  58.             request.LongitudeSpecified = true;  
  59.             request.Radius = 10.0;  
  60.             request.RadiusSpecified = true;  
  61.             request.Options = new SearchOption { SearchOption.EnableHighlighting };  
  62.  
  63.             // Phonebook-specific request fields (optional)  
  64.             request.Phonebook = new PhonebookRequest();  
  65.             request.Phonebook.Count = 10;  
  66.             request.Phonebook.CountSpecified = true;  
  67.             request.Phonebook.Offset = 0;  
  68.             request.Phonebook.OffsetSpecified = true;  
  69.             request.Phonebook.FileType = "YP";  
  70.             request.Phonebook.SortBy = PhonebookSortOption.Distance;  
  71.             request.Phonebook.SortBySpecified = true;  
  72.  
  73.             return request;  
  74.         }  
  75.  
  76.         static void DisplayErrors(XmlNode errorDetails)  
  77.         {  
  78.             // Add the default namespace to the namespace manager.  
  79.             XmlNamespaceManager nsmgr = new XmlNamespaceManager(errorDetails.OwnerDocument.NameTable); nsmgr.AddNamespace("api""http://schemas.microsoft.com/LiveSearch/2008/03/Search");  
  80.  
  81.             XmlNodeList errors = errorDetails.SelectNodes("./api:Errors/api:Error", nsmgr);  
  82.  
  83.             if (errors != null)  
  84.             {  
  85.                 // Iterate over the list of errors and display error details.  
  86.                 Console.WriteLine("Errors:");  
  87.                 Console.WriteLine();  
  88.                 foreach (XmlNode error in errors)  
  89.                 {  
  90.                     foreach (XmlNode detail in error.ChildNodes)  
  91.                     {  
  92.                         Console.WriteLine(detail.Name + ": " + detail.InnerText);  
  93.                     }  
  94.  
  95.                     Console.WriteLine();  
  96.                 }  
  97.             }  
  98.         }  
  99.     }  

代码中使用的AppId需要去Bing Developer Center申请(免费),上面的AppId是我在测试代码的时候申请的,应该可以使用。接下来我们需要在工程中创建两个Web Page来测试这两个类,下面是这两个页面的测试代码(HTML & C#): 

WebSourceType.aspx

  1. <h2>  
  2.     Using the Web SourceType Over the SOAP Protocol</h2>  
  3. This example shows how to perform the following tasks:  
  4. <ul>  
  5.     <li>Set search request basic parameters by using the <a href="http://msdn.microsoft.com/en-us/library/dd250960.aspx"  
  6.         target="_blank">SearchRequest</a> type.</li>  
  7.     <li>Set the Web book request by using the <a href="http://msdn.microsoft.com/en-us/library/dd250886.aspx"  
  8.         target="_blank">WebRequest</a> type. </li>  
  9.     <li>Display the results obtained from the <a href="http://msdn.microsoft.com/en-us/library/dd250843.aspx"  
  10.         target="_blank">SearchResponse</a> type. </li>  
  11. </ul>  
  12. <h4>  
  13.     See Also  
  14. </h4>  
  15. <span style="background-color: Yellow"><a href="http://msdn.microsoft.com/en-us/library/dd251056.aspx"  
  16.     target="_blank">BING API</a></span>  
  17. <br />  
  18. <br />  
  19. <span style="background-color: Yellow">For more information, see <a href="http://blogs.msdn.com/morebits/"  
  20.     target="_blank">Technical Notes</a></span>  
  21. <br />  
  22. <br />  
  23. <asp:Table ID="WebResultID" BorderWidth="1" runat="server">  
  24.     <asp:TableHeaderRow BackColor="LightGray">  
  25.         <asp:TableCell ID="hdrID1" BorderStyle="Inset" />  
  26.     </asp:TableHeaderRow>  
  27. </asp:Table> 

WebSourceType.aspx.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using BingSearchDemo.net.live.search.api;  
  8.  
  9. namespace BingSearchDemo  
  10. {  
  11.     public partial class WebSourceType : System.Web.UI.Page  
  12.     {  
  13.         protected void Page_Load(object sender, EventArgs e)  
  14.         {  
  15.  
  16.         }  
  17.  
  18.         // Get the search results. Display one result per row.  
  19.         private void DisplayResults(SearchResponse response)  
  20.         {  
  21.             int j = 0;  
  22.             foreach (WebResult result in response.Web.Results)  
  23.             {  
  24.                 TableRow tRow = new TableRow();  
  25.                 WebResultID.Rows.Add(tRow);  
  26.                 TableCell tCell = new TableCell();  
  27.                 tCell.BorderWidth = Unit.Parse("1");  
  28.                 if (j % 2 == 0)  
  29.                     tCell.BackColor = System.Drawing.Color.Blue;  
  30.                 else  
  31.                     tCell.BackColor = System.Drawing.Color.Tomato;  
  32.                 tCell.ForeColor = System.Drawing.Color.Yellow;  
  33.                 tCell.Font.Bold = true;  
  34.                 System.Text.StringBuilder builder = new System.Text.StringBuilder();  
  35.                 builder.AppendLine(result.Title);  
  36.                 builder.AppendLine(result.Description);  
  37.                 builder.AppendLine(result.Url);  
  38.                 builder.Append("Last Crawled: ");  
  39.                 builder.AppendLine(result.DateTime);  
  40.                 j++;  
  41.                 int i = 0;  
  42.                 foreach (char c in builder.ToString().ToCharArray())  
  43.                 {  
  44.                     if (c == '\uE000')  
  45.                     {  
  46.                         // If the current character is the begin highlighting  
  47.                         // character (U+E000), change it to a left square bracket.  
  48.                         builder[i] = Convert.ToChar('[');  
  49.                     }  
  50.                     else if (c == '\uE001')  
  51.                     {  
  52.                         // If the current character is the end highlighting  
  53.                         // character (U+E001), change it to a right square bracket.  
  54.                         builder[i] = Convert.ToChar(']');  
  55.                     }  
  56.                     i++;  
  57.                 }  
  58.                 tCell.Text = builder.ToString();  
  59.                 tRow.Cells.Add(tCell);  
  60.             }  
  61.         }  
  62.  
  63.         protected override void OnPreRender(EventArgs e)  
  64.         {  
  65.             base.OnPreRender(e);  
  66.             SearchResponse response = UsingWebSourceType.PerformLiveSearch();  
  67.             string results = string.Format("Displaying {0} to {1} of {2} results", response.Web.Offset + 1,  
  68.                            response.Web.Offset + response.Web.Results.Length, response.Web.Total);  
  69.             // Add header information to the table.  
  70.             hdrID1.Text = "<div style='color:red; font-weight:bold'>Bing API Version: " + response.Version + "</div>" +  
  71.                             "<div style='color:red; font-weight:bold'>Web results for " + response.Query.SearchTerms + "</div>" +  
  72.                             "<div style='color:red; font-weight:bold'>" + results + "</div>";  
  73.             // Add rows to the table that contain search results.  
  74.             DisplayResults(response);  
  75.         }  
  76.     }  

PhonebookSourceType.aspx

  1. <h2>  
  2.     Using the Web SourceType Over the SOAP Protocol</h2>  
  3. This example shows how to perform the following tasks:  
  4. <ul>  
  5.     <li>Set search request basic parameters by using the <a href="http://msdn.microsoft.com/en-us/library/dd250960.aspx"  
  6.         target="_blank">SearchRequest</a> type.</li>  
  7.     <li>Set the Web book request by using the <a href="http://msdn.microsoft.com/en-us/library/dd250886.aspx"  
  8.         target="_blank">WebRequest</a> type. </li>  
  9.     <li>Display the results obtained from the <a href="http://msdn.microsoft.com/en-us/library/dd250843.aspx"  
  10.         target="_blank">SearchResponse</a> type. </li>  
  11. </ul>  
  12. <h4>  
  13.     See Also  
  14. </h4>  
  15. <span style="background-color: Yellow"><a href="http://msdn.microsoft.com/en-us/library/dd251056.aspx"  
  16.     target="_blank">BING API</a></span>  
  17. <br />  
  18. <br />  
  19. <span style="background-color: Yellow">For more information, see <a href="http://blogs.msdn.com/morebits/"  
  20.     target="_blank">Technical Notes</a></span>  
  21. <br />  
  22. <br />  
  23. <asp:Table ID="WebResultID" BorderWidth="1" runat="server">  
  24.     <asp:TableHeaderRow BackColor="LightGray">  
  25.         <asp:TableCell ID="hdrID1" BorderStyle="Inset" />  
  26.     </asp:TableHeaderRow>  
  27. </asp:Table> 

PhonebookSourceType.aspx.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using BingSearchDemo.net.live.search.api;  
  8.  
  9. namespace BingSearchDemo  
  10. {  
  11.     public partial class PhonebookSourceType : System.Web.UI.Page  
  12.     {  
  13.         protected void Page_Load(object sender, EventArgs e)  
  14.         {  
  15.  
  16.         }  
  17.  
  18.         // Get the search results. Display one result per row.  
  19.         private void DisplayResults(SearchResponse response)  
  20.         {  
  21.             int j = 0;  
  22.             foreach (PhonebookResult result in response.Phonebook.Results)  
  23.             {  
  24.                 TableRow tRow = new TableRow();  
  25.                 WebResultID.Rows.Add(tRow);  
  26.                 TableCell tCell = new TableCell();  
  27.                 tCell.BorderWidth = Unit.Parse("1");  
  28.                 if (j % 2 == 0)  
  29.                     tCell.BackColor = System.Drawing.Color.Blue;  
  30.                 else  
  31.                     tCell.BackColor = System.Drawing.Color.Tomato;  
  32.                 tCell.ForeColor = System.Drawing.Color.Yellow;  
  33.                 tCell.Font.Bold = true;  
  34.                 System.Text.StringBuilder builder = new System.Text.StringBuilder();  
  35.                 builder.AppendLine(result.Business);  
  36.                 builder.AppendLine(result.Address);  
  37.                 builder.Append(result.City);  
  38.                 builder.Append(", ");  
  39.                 builder.AppendLine(result.StateOrProvince);  
  40.                 builder.AppendLine(result.PhoneNumber);  
  41.                 builder.Append("Average Rating: ");  
  42.                 builder.AppendLine(result.UserRating.ToString());  
  43.  
  44.                 j++;  
  45.                 int i = 0;  
  46.                 foreach (char c in builder.ToString().ToCharArray())  
  47.                 {  
  48.                     if (c == '\uE000')  
  49.                     {  
  50.                         // If the current character is the begin highlighting  
  51.                         // character (U+E000), change it to a left square bracket.  
  52.                         builder[i] = Convert.ToChar('[');  
  53.                     }  
  54.                     else if (c == '\uE001')  
  55.                     {  
  56.                         // If the current character is the end highlighting  
  57.                         // character (U+E001), change it to a right square bracket.  
  58.                         builder[i] = Convert.ToChar(']');  
  59.                     }  
  60.                     i++;  
  61.                 }  
  62.                 tCell.Text = builder.ToString();  
  63.                 tRow.Cells.Add(tCell);  
  64.             }  
  65.         }  
  66.  
  67.         protected override void OnPreRender(EventArgs e)  
  68.         {  
  69.             base.OnPreRender(e);  
  70.             SearchResponse response = UsingPhonebookSourceType.PerformLiveSearch();  
  71.             string results = string.Format("Displaying {0} to {1} of {2} results", response.Phonebook.Offset + 1,  
  72.                            response.Phonebook.Offset + response.Phonebook.Results.Length, response.Phonebook.Total); 
  73.             // Add header information to the table.  
  74.             hdrID1.Text = "<div style='color:red; font-weight:bold'>Bing API Version: " + response.Version + "</div>" +  
  75.                             "<div style='color:red; font-weight:bold'>Phonebook results for " + response.Query.SearchTerms + "</div>" +  
  76.                             "<div style='color:red; font-weight:bold'>" + results + "</div>";  
  77.             // Add rows to the table that contain search results.  
  78.             DisplayResults(response);  
  79.         }  
  80.     }  

 

下面是在我机器上使用上面两种类型执行查询的结果:

1

 

2

  Bing Search Service API的详细介绍和SDK文档可以去Bing Developer Center

设为首页 | 加入收藏 | 网学首页 | 原创论文 | 计算机原创
版权所有 网学网 [Myeducs.cn] 您电脑的分辨率是 像素
Copyright 2008-2020 myeducs.Cn www.myeducs.Cn All Rights Reserved 湘ICP备09003080号 常年法律顾问:王律师