你会自定义SOAP头消息吗?

先请大家看一篇文章: Get a Handle on SOAP Headers
http://www.aspnetpro.com/features/2002/10/asp200210dw_f/asp200210dw_f.asp

通过这篇文章,大家可以学习到在.Net环境下如何获取对SOAP消息头的操作,并对SOAP消息进行自定义,加进自己的功能!这在开发涉及安全、身份认证、附件传输等Web Services的时候非常有用!由于时间关系,我没来得及翻译,见谅!

作者在例程中自定义了一个标记authenticationtoken来存放唯一标识注册用户身份的信息,通过对一个从SoapHeader继承下来的类AuthenticationHeader的处理,将标记信息添加到用户向服务器提交的SOAP认证消息的头部,形成了如下的消息格式:

 1<soap:envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 2<soap:header>
 3<authenticationheader xmlns="http://www.xmlforasp.net">
 4<authenticationtoken>   
 5a49d0f16-8880-45f3-99dd-434eb640ecfa   
 6</authenticationtoken>
 7</authenticationheader>
 8</soap:header>
 9<soap:body>
10<getaccountdetails xmlns="http://www.xmlforasp.net">
11<accountid>123456789</accountid>
12</getaccountdetails>
13</soap:body>
14</soap:envelope>

然后,在Web Services端,在Web Method中添加一个对SoapHeader属性扩展的引用:
[WebMethod]
//Header only used as input to a Web Method
[SoapHeader("AuthHeader", Direction=SoapHeaderDirection.In,
Required=true)]
public Account GetAccountDetails(int accountID) {
。。。
Account ad = new Account(accountID,AuthHeader.AuthenticationToken);
。。。
}

将一个SoapHeader属性类(即中括号中的部分)与一个WebMethod(即GetAccountDetails)关联起来,目的是为了用SoapHeader类(即AuthHeader)获取提交请求的SOAP消息中的头信息,得到标识用户的AuthenticationToken的值(AuthHeader.AuthenticationToken),并进一步处理进行身份验证!

这里只是简单介绍了如何自定义SOAP头消息,其实SOAP消息的其他部分也都可以自己灵活定义,处理框架大致一样,只是使用的属性类有所区别。理论上SOAP消息可以定义成任何有效的XML格式^_^

我将作者提供的原代码进行了修改,形成了两个单独项目,结构层次分明,一个是实现身份验证的Web Services——SoapHeaderDemoWebService,一个是实现用户登陆的客户端——SoapHeaderClient,它将访问Web Services。

先将我提供的文件 http://www.downsky.net/ut/attach/2002/10/28/558996-SoapHeaderDemo.rar 解压后的两个目录拷到Inetpub\wwwroot下,然后在SQL Server中建个数据库SoapHeaderTest,在Query Analyzer中执行SoapHeaderDemoWebService目录下的脚本文件SOAPHeaders.sql,最后浏览:
http://localhost/SoapHeaderClient/SoapHeaderDemoClient.aspx
可看到运行效果!当然前提是安装了.Net环境!

另外,可以直接在
http://www.xmlforasp.net/CodeBank/WebServices/SOAPHeaders/SoapHeaderDemoClient.aspx 看到这个例子!

Published At
Categories with Web编程
Tagged with
comments powered by Disqus