65.9K
CodeProject 正在变化。 阅读更多。
Home

如何从 .Net 消费者和非 .Net 消费者调用 Microsoft .Net Web 服务

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (23投票s)

2006年2月12日

6分钟阅读

viewsIcon

168852

downloadIcon

1086

当我第一次接触 Microsoft .Net Web 服务时,我很难了解如何在 ASP 代码中利用用 C#、VB.Net 等 .Net 语言实现的 Web 服务,以及不同的 Web 协议...

当我第一次接触 Microsoft .Net Web 服务时,我很难了解如何在 ASP 代码中利用用 C#、VB.Net 等 .Net 语言实现的 Web 服务,以及用于通信的不同 Web 协议总是让我感到困惑。

本文一定会帮助那些刚踏入 Web 服务世界的初学者。

假设

读者必须了解 Web 服务的架构以及如何通过 Microsoft Visual Studio .Net 创建 Web 服务。此外,读者必须具备 XML 的基本知识。

引言

概述:

Web 服务允许通过 HTTP 和 SMTP 等标准协议访问软件组件。通过使用互联网和 XML,我们现在可以创建与其他软件组件通信的软件组件,无论语言、平台如何。

DCOM 与 Web 服务的比较

DCOM 和 Web 服务都是用于创建分布式组件的,但 Web 服务与 DCOM(又称 COM over wire)相比的主要优势在于,只要任何应用程序使用标准 Web 协议并理解 XML 编码的消息,它就可以访问 Web 服务,无论平台如何。

Web 服务客户端(又称消费者)通过 HTTP Post、HTTP Get 和 SOAP 等标准协议与 Web 服务通信。接下来我们将演示如何构建利用这些协议的客户端应用程序。

描述

为了理解这个概念,我们首先将创建一个简单的 Web 服务提供者,然后,通过使用这个 Web 服务,我们将看到它如何被消费。

Web 服务提供者

Web 服务提供者实现 Web 服务并进行宣传,以便客户端可以发现和使用这些服务。由于 Web 服务运行在 HTTP 之上,因此托管 Web 服务的机器上必须有某种 Web 服务器应用程序。这个 Web 服务器应用程序可以是 Microsoft Internet Information Services (IIS)、Apache 或任何其他可以理解和处理 HTTP 协议的程序。在我们的示例中,我们使用 Microsoft IIS,因为它是 .NET 目前唯一支持的 Web 服务器。稍后,我们将看到它如何被消费。

下面,我们描述了最简单的 Web 服务之一的代码,存储在“Service.asmx”文件中,其中包含两个 Web 方法

方法名称

参数

返回类型

注释

HelloWorld

字符串

返回“Hello World”

HelloWorldWithCustomMessage

@s_Msg – 字符串

字符串

将参数字符串与“Hello World”附加并返回。

当然,所有 Web 方法的访问修饰符都将是 public。

代码片段

 
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

[WebService(Namespace = "http://tempuri.org/">http://tempuri.org/")]
public class Service : System.Web.Services.WebService
{
    public Service () {
    }

    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }

"MsoNormal" style="MARGIN: 0in 0in 0pt">    [WebMethod]
    public string HelloWorldWithCustomMessage(string s_Msg)
    {
        return "Hello World " + s_Msg;
    }
}

注意:我假设 IIS 服务器可以通过 https:/// 链接访问,并且我们将上面创建的 Web 服务部署在名为“HelloWorldWS”的虚拟目录下。

Web 服务消费者

在上面的部分中,我们成功创建了 Web 服务提供者,让我们看看 Web 客户端如何使用这个 Web 服务。

HTTP Get 消费者(Web 浏览器):

这个消费者是最简单的。如果我们将 Web 浏览器指向 Web 服务 URL (https:///HelloWorldWS/Service.asmx),它将为我们提供支持的 Web 方法列表。

<formulas></formulas>

Sample screenshot

要了解有关这些方法的更多信息,请单击其中一个。这将弹出一个默认的 Web 服务消费者。这个消费者是使用反射自动生成的,非常适合测试您的 Web 服务方法。它使用 HTTP GET 协议与 Web 服务通信。这个消费者有一个表单,可以测试该方法(参见图),以及如何通过 SOAP、HTTP GET 或 HTTP POST 访问该方法的描述(当我们通过非 .Net 消费者调用 Web 服务时,我们可以将此信息作为参考)。

Sample screenshot

(图 – HelloWorldWithCustomMessage 方法测试)

消费起来非常简单……是吧?

.Net 消费者

HTTP Post 协议

在上一节中,我们已经看到创建 HTTP Get 消费者只需访问 Web 服务的 URL。接下来,我们将看到如何编写可以使用 HTTP Post 和 SOAP 访问 Web 服务的消费者代码。

注意:我们将使用 C# 代码来消费 Web 服务。

使用 Web 服务的步骤

I) 生成 Web 服务代理代码

Microsoft.net SDK 提供了各种工具来简化创建或消费 Web 服务的流程。与 Web 服务一起使用的最重要的工具之一是 WSDL.EXE。WSDL 工具将 WSDL 文件作为输入,并为消费者创建代理。

以下是我们用于为 Web 服务“HelloWorldWS/Service.asmx”创建代理文件的确切命令

Wsdl /l:cs /protocol:HTTPPost https:///HelloWorldWS/Service.asmx?wsdl


/l:cs – 指定语言类型
/protocol:HTTPPost – 指定协议类型;我们也可以使用 /protocol:HTTPGet 或 /protocol:SOAP 参数。
URL – WSDL 文件的位置。

它将生成包含代理代码的 Service.cs 文件。

简要介绍代理:代理源代码类似于 IDL 编译器为 DCOM 代理生成源代码文件的方式。

注意:如果您查看这个生成的 C# 文件,您会看到它包含一个从 HttpPostClientProtocol 类派生的代理类 Service。如果您使用 /protocol:HttpGet 或 /protocol:SOAP 参数,那么 Service 将分别从 HttpGetClientProtocol 或 SoapHttpClientProtocol 类派生。

II) 创建代理后,我们的下一个任务是利用代理。要利用代理,我首先编译代理,创建 DLL 文件,然后在编译消费者时引用 DLL。



创建 DLL 文件

Csc /target:library Service.cs

它将创建 Service.dll

编写消费者代码

我写了一个简单的

Sample screenshot


编译带有 DLL 引用的消费者

csc /r:Service.dll CallHelloWorldWS_SOAP_Using_Proxy.cs

执行 CallHelloworldWS_SOAP_Using_Proxy.exe

csc CallhelloWorldws_Soap_Using_Proxy

输出:Hello World

您可能会想,当我们要通过消费者代码利用 Web 服务时,为什么需要遵循这么多步骤。

实际上,当消费者代码不是 .Net 语言时,需要这些步骤。但是,如果您想将其用于任何 Microsoft .Net 语言(VB.net、C#、Managed C++、Jscript)并且您拥有 Microsoft Visual Studio .Net IDE,那么您只需发现并添加 Web 服务引用即可。其余的任务将由 VS.Net IDE 处理——好的,读完这句话,我相信 90% 的读者会欣赏 VS.Net IDE,并且不会远离本文 :)。

非 .Net 消费者

本节展示了如何使用 HTTP GET、HTTP POST 和 SOAP 协议开发非 .NET Web 服务消费者。

我们使用了 ASP 非 .Net 语言,对于那些有兴趣从其他非 .Net 语言(如 PERL)调用 Web 服务的人,他们需要找到 XMLHTTP 组件的替代品。

HTTP Get 协议

目的是使用 XMLHTTP 组件调用互联网上可用的网页/代码,并将结果返回给调用者。

评论:我们也可以使用免费的 ASPTear 组件代替 XMLHTTP。

下面的代码片段不言自明

<%

Dim o_XmlhttpCaller




' Create Object of MSXml2.XMLHTTP

Set o_XmlhttpCaller = Server.CreateObject("Msxml2.XMLHTTP")

' Check whether object created successfully.

If ( o_XmlhttpCaller is nothing ) Then

Response.Write("<font color=red size=-1>Unable to create Object - 
Type: Msxml2.XMLHTTP<BR></font>")




Response.Write("Solution: Install MSXML 4.0")

End If

'Open method will take three arguments

'@Param1

'Method - POST or GET

'@Param2

'URL - Uniform Resource Locator 

' It must be a valid URL (check by visiting through Iexplore or any browser)

'@Params3

'Async - If true then the call would be asynchronous, else Synchronous.

o_XmlhttpCaller.open "GET","https:///WSHelloWorld/Service.asmx/
HelloWorldWithCustomMessage?s_msg= Hope you like this article.", False

'Make call to the web service. 

o_XmlhttpCaller.send

'Okay, play return data according to your need.

' I response back to browser as it is.

Response.Write(o_XmlhttpCaller.responseText)

' Time to clean the mess manually:-/ Ahh... can we request Microsoft to 
build GC for ASP? :)

Set o_XmlhttpCaller = nothing

%> 
HTTP Post 协议

HTTP POST 和 HTTP Get 协议的实现思路将保持不变,除了上面代码中的一些更改。

这是更改后的代码行

'@Param1

'Method - POST or GET

' POST can be use when we do not want to send data as form submission

'@Param2

'URL - Uniform Resource Locator 

' It must be a valid URL (check by visiting through Iexplore or any browser)

'@Params3

'Async - If true then the call would be asynchronous, else Synchronous.

'This time we are not passing query string with URL.

o_XmlhttpCaller.open "POST","https:///WSHelloWorld/Service.asmx/
HelloWorldWithCustomMessage", False

' XMLHTTP by default pass data in the form of XML, 

' and it require to set Content-Type = "application/x-www-form-urlencoded".

o_XmlhttpCaller.setRequestHeader "Content-Type", 
"application/x-www-form-urlencoded"
'Make call, and pass form value with variable name that expected by the 
web service(If any).

' NOTE: Variable Name must match with web method parameter!!

o_XmlhttpCaller.send("s_Msg= I hope this article will help .Net 
Champions somewhere:-)")

SOAP 协议

正如我们上面所做的,使用 SOAP 协议也是一样的,但这里我们传递结构化消息 - SOAP 消息。

如果您还记得,通过 Web 浏览器测试“HelloWorldWithCustomMessage”方法时,我们看到了与 Web 服务通信所期望的 SOAP 消息格式。下面代码中使用了相同的 SOAP 格式

'This line is different than HTTP Post code 

'We are not telling which action require to call , because the SOAP header 
(see below) contain this information.

o_XmlhttpCaller.open "POST","https:///WSHelloWorld/Service.asmx">http://localhost/WSHelloWorld/Service.asmx, 
False

'This time we will set content-type to XML because, SOAP message in the 
form of XML.

o_XmlhttpCaller.setRequestHeader "Content-Type", "text/xml"


'Here is what we are setting soap action that require to call

o_XmlhttpCaller.setRequestHeader "SOAPAction","http://tempuri.org/
HelloWorldWithCustomMessage"
'Prepare soap message

Dim soapMessage 

soapMessage = "<soap:Envelope 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">"

soapMessage = soapMessage & "<soap:Body>"

soapMessage = soapMessage & 
"<HelloWorldWithCustomMessage xmlns=""http://tempuri.org/"">"

soapMessage = soapMessage & "<s_Msg> I hope this article will help 
.Net Champions somewhere:-)</s_Msg>"

soapMessage = soapMessage & "</HelloWorldWithCustomMessage>"

soapMessage = soapMessage & "</soap:Body>"

soapMessage = soapMessage & "</soap:Envelope>"
'Make call to the web service with soap message.

o_XmlhttpCaller.send(soapMessage)
'Okay, play return data according to your need.

' I response back to browser as it is.

' Data would be in XML format, so it would be good to transform to
 XHTML with the help of 

' XSL.

Response.Write(o_XmlhttpCaller.responseText)

' Alright, time to clean the mess manually:-/ Ahh... can we request Microsoft
 to build GC for ASP? :)

Set o_XmlhttpCaller = nothing 


结论

在本文中,我们已经看到了可用于消费 Web 服务的不同协议,以及我们如何从 .Net 和非 .Net 语言调用 Web 服务。

如果您从本文中学到了任何东西,请投票。

如何从 .Net 消费者和非 .Net 消费者调用 Microsoft .Net Web 服务 - CodeProject - 代码之家
© . All rights reserved.