在这个例子中,我们会使用ASP.NET来创建一个简单的Web Service。
<%@ WebService Language="VB" Class="TempConvert" %> Imports System Imports System.Web.Services Public Class TempConvert :Inherits WebService <WebMethod()> Public Function FahrenheitToCelsius (ByVal Fahrenheit As Int16) As Int16 Dim celsius As Int16 celsius = ((((Fahrenheit) - 32) / 9) * 5) Return celsius End Function <WebMethod()> Public Function CelsiusToFahrenheit (ByVal Celsius As Int16) As Int16 Dim fahrenheit As Int16 fahrenheit = ((((Celsius) * 9) / 5) + 32) Return fahrenheit End Function End Class
此文档是一个.asmx文件。这是用于XML Web Services的ASP.NET文件扩展名。
此文档中第一行表明这是一个Web Service,由VB编写,其class名称是"TempConvert"。
<%@ WebService Language="VB" Class="TempConvert" %>
接下来的代码行从.NET框架导入了命名空间"System.Web.Services"。
Imports System Imports System.Web.Services
下面这一行定义"TempConvert"类是一个WebSerivce类:
Public Class TempConvert :Inherits WebService
接下来的步骤是基础的VB编程。此应用程序有两个函数。一个把华氏度转换为摄氏度,而另一个把摄氏度转换为华氏度。
与普通的应用程序唯一的不同是,此函数被定义为"WebMethod"。
请在您希望其成为web services的应用程序中使用"WebMethod"来标记函数。
<WebMethod()> Public Function FahrenheitToCelsius (ByVal Fahrenheit As Int16) As Int16 Dim celsius As Int16 celsius = ((((Fahrenheit) - 32) / 9) * 5) Return celsius End Function <WebMethod()> Public Function CelsiusToFahrenheit (ByVal Celsius As Int16) As Int16 Dim fahrenheit As Int16 fahrenheit = ((((Celsius) * 9) / 5) + 32) Return fahrenheit End Function
最后要做的事情是终止函数和类:
End Function End Class
假如您把此文件另存为.asmx文件,并发布于支持.NET的服务器上,那么您就拥有了第一个可工作的Web Service。
通过ASP.NET,你不必亲自编写WSDL和SOAP文档。
如果您仔细研究我们的这个例子,您会发现ASP.NET会自动创建WSDL和SOAP请求。
Web Service 使用
您可以使用这些代码把web service放置在您的站点上:
<form target="_blank"
action='http://www.w3schools.com/webservices/tempconvert.asmx/FahrenheitToCelsius'
method="POST">
<label>华氏度转换为摄氏度:</label>
<p>
<span>
<input class="frmInput" type="text" size="30" name="Fahrenheit">
</span>
<span>
<input type="submit" value="提交" class="button">
</span>
</p>
</form>
<form target="_blank"
action='http://www.webjx.com/webservices/tempconvert.asmx/CelsiusToFahrenheit'
method="POST">
<label>摄氏度转换为华氏度:</label>
<p>
<span>
<input class="frmInput" type="text" size="30" name="Celsius">
</span>
<span>
<input type="submit" value="提交" class="button">
</span>
</p>
</form>
本教程已经向您讲解了如何把应用程序转换为网络应用程序.
您已经学习了如何使用XML在应用程序间发送消息。
您也学习了如何从应用程序导出某项功能(创建一个web service)。
下一步您应当学习WSDL和SOAP。
WSDL是基于XML的用来描述Web services以及如何访问它们的一种语言。
WSDL可描述web service,连同用于web service的消息格式和协议的细节。
SOAP是一种使应用程序有能力通过HTTP交互信息的基于XML的简易协议。
或者可以更简单地说:SOAP是一种用于访问web service的协议。