| 通过Web Services提供内容服务 |
|
作者:甘冀平 文章来源:yesky.com 点击数: 更新时间:2005-5-17 22:58:03  |
一、引 言
对于Web Services是什么已经如何进行简单的应用,我们已经有所了解。现在,Web内容提供商们正在充分发掘Web Services的潜力,将它作为信息发布的一个重要部件。
我们知道,许多门户网站,比如Yahoo、Excite,都提供每日更新的新闻信息、体育信息、股票信息、游戏信息、天气信息以及Email信息。但实际上,并非每个方面的内容最初都由该门户网站真正创建,它们只是订阅了其他提供特殊信息的网站的内容,然后再加工而成。现在你就不会奇怪:为什么当你浏览门户网站的这些信息时,会感觉到内容似曾相识。
提供这些特殊信息的网站被称为ICP(Internet Content Providers),也就是"Internet内容提供商"。通常,ICP除了为门户网站提供这些特殊信息外,也会为一般访问者提供这些内容。因此,如何采取有效的技术手段为外界提供信息服务,成为ICP面对的非常重要的课题。
下面我们就介绍一个可被ICP采用的用于此种信息提供的Web Services,这个Web Services将负责递送每日占星(诞生时的星位)的信息。注意,因为我们都不是占星行家,所以这里的Web Services仅仅是一个框架性的描述。要想真正地应用,还需要"占星家"的帮助哦)
二、服务器端和客户端的工作状态描述
A) 服务器端
占星的资料每日由工作人员更新,存储在叫做dailyhoro.xml的文件中,XML数据库放置于DB子目录中。
B) 客户端
客户端可以通过Web页面或者应用程序查看他们的占星信息。客户端提供Zodiac Sign信息后,Web Services接受请求进行处理,最后发送给访问者他们的每日阅读信息。
三、Web Service源代码分析
首先我们看一下这个Web Service的源代码,文件名为wshoro.asmx,它将一个含有"Zodiac Sign"的字符串作为输入参数,然后在数据库中对这个字符串信息进行搜索,如果发现了匹配信息,就返回一个包含日期的字符串和对应的预言信息。关于zodiac sign,我们只需知道它包含如下的12种命名: Aquarius, Pisces, Aries, Taurus, Gemini, Cancer, Leo, Virgo, Libra, Scorpio, Capricorn, and Sagittarius。
首先是引入必需的名字空间:
<%@ Webservice Language="C#" class="DailyHoro" %> using System ; using System.Web.Services ; using System.Xml ; using System.Data; using System.IO ; | 然后声明一个类DailyHoro,它从System.Web.Services 名字空间中延伸了WebSerice类的功能:
public class DailyHoro : WebService { .... ..... } | 类DailHoro 包含一个公共方法GetHoro,这个方法又被标记为WebMethod属性,这表明了它可以作为一个Web Service被公开访问。GetHoro方法的输入参数是包含zodiac sign信息的字符串,然后将这个字符串传递给另外的私有方法getData,最后由getData方法返回信息给用户:
[WebMethod] public string GetHoro(string zodiac) { return getData(zodiac) ; } | getData方法在GetHoro方法中被调用。首先打开一个Filesteam文件流用于读取XML数据库文件的内容,然后使用DataSet对象从XML文件中读取数据,接着对DataSet的所有行循环操作,以找到匹配Zodiac Sign的相关信息。寻找成功后,当前日期和对应的预言内容被返回。否则,返回相应的错误信息:
private string getData(string zodiac) { try { file://Create a FileStream FileStream fin ; fin= new FileStream(Server.MapPath("db/dailyhoro.xml"), FileMode.Open, FileAccess.Read,FileShare.ReadWrite );
file://Create a DataSet object to contain our Database DataSet ds = new DataSet() ;
file://Read the Xml Schema and Data from the stream to the Database file ds.ReadXml(new StreamReader(fin)) ;
file://close the stream fin.Close() ;
file://loop to check for the Zodiac sign provided for(int i=0;i<12 ; i++) { file://Check if the Zodiac sign provided by the user Equals file://the "name" field in our Table "zodiac" if(zodiac.Equals(ds.Tables[0].Rows[i]["name"])) { file://If a match if found then return the Date and file://Prediction string pred =ds.Tables[0].Rows[i]["pred"].ToString() ; string date = ds.Tables[0].Rows[i]["today"].ToString() ; return date+"@"+pred ; } }
file://If no match found then return a error statement return "Wrong Parameter" ; } catch(Exception ed) { return "Read Error!!"+ed.ToString() ; } } |
[1] [2] 下一页 |
| 文章录入:admin 责任编辑:admin |
|
上一篇文章: Web Service故障处理
下一篇文章: 关于C#下写的Web Service 服务在Delphi下调用时的问题 |
| 【字体:小 大】【发表评论】【加入收藏】【告诉好友】【打印此文】【关闭窗口】 |