Web Services 예제

任何应用程序都可拥有 Web Service 组件。

Web Services 的创建与编程语言的种类无关。

一个实例:ASP.NET Web Service

在这个例子中,我们会使用 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 文件扩展名。

要运行这个例子,我们需要一个 .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의 자동 처리

ASP.NET를 통해 WSDL과 SOAP 문서를 직접 작성할 필요가 없습니다.

이 예제를 자세히 연구하면 ASP.NET가 자동으로 WSDL과 SOAP 요청을 생성한다는 것을 발견할 수 있습니다.