Web Service 实例

本节通过相应的实例来让您更加了解 Web Service 的使用。

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

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

一个实例:ASP.NET Web Service

在这个例子中,我们会使用 ASP.NET 来创建一个简单的 Web Service。

<%@ WebService Language=”VBScript” Class=”TempConvert” %>Imports System
Imports System.Web.Services

Public Class TempConvert :Inherits WebService

<WebMethod()> Public Function FahrenheitToCelsius
(ByVal Fahrenheit As String) As String
dim fahr
fahr=trim(replace(Fahrenheit,”,”,”.”))
if fahr=”” or IsNumeric(fahr)=false then return “Error”
return ((((fahr) – 32) / 9) * 5)
end function

<WebMethod()> Public Function CelsiusToFahrenheit
(ByVal Celsius As String) As String
dim cel
cel=trim(replace(Celsius,”,”,”.”))
if cel=”” or IsNumeric(cel)=false then return “Error”
return ((((cel) * 9) / 5) + 32)
end function

end class

此文档是一个 .asmx 文件。这是用于 XML Web Services 的 ASP.NET 文件扩展名。

实例 Explained

注意: 要运行这个例子,我们需要一个 .NET 服务器

此文档中第一行表明这是一个 Web Service,由 VB 编写,其 class 名称是 “TempConvert”。

<%@ WebService Language=”VBScript” 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 String) As String
dim fahr
fahr=trim(replace(Fahrenheit,”,”,”.”))
if fahr=”” or IsNumeric(fahr)=false then return “Error”
return ((((fahr) – 32) / 9) * 5)
end function

<WebMethod()> Public Function CelsiusToFahrenheit
(ByVal Celsius As String) As String
dim cel
cel=trim(replace(Celsius,”,”,”.”))
if cel=”” or IsNumeric(cel)=false then return “Error”
return ((((cel) * 9) / 5) + 32)
end function

最后要做的事情是终止函数和类:

end class

假如您把此文件另存为 .asmx 文件,并发布于支持 .NET 的服务器上,那么您就拥有了第一个可工作的 Web Service。

ASP.NET 的自动化处理

通过 ASP.NET,你不必亲自编写 WSDL 和 SOAP 文档。

如果您仔细研究我们的这个例子,您会发现 ASP.NET 会自动创建 WSDL 和 SOAP 请求。

作者:冒牌SEO,如若转载,请注明出处:https://www.web176.com/webservice/10475.html

(0)
打赏 支付宝 支付宝 微信 微信
冒牌SEO冒牌SEO
上一篇 2023年2月24日
下一篇 2023年2月24日

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注