[.NET][C#]dotNet使用WSE3.0调用java的web服务

来源:互联网 发布:p2p网络借贷的起源 编辑:程序博客网 时间:2024/05/16 19:11

本文主要描述使用.net客户端调用java写的服务端的webservice,并且使用了WSI协议中的UserNameToken验证方法。

 

先给出要POST的包格式:

  1. <soap:Envelope xmlns:soap="…">
  2.     <soap:Header>
  3.         <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
  4.             <wsse:UsernameToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="SecurityToken-7f2cd499-d67d-4052-87c3-870833c2fb06">
  5.                 <wsse:Username>much</wsse:Username>
  6.                 <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">123456</wsse:Password>
  7.             </wsse:UsernameToken>
  8.         </wsse:Security>
  9.         <RequestSOAPHeader xmlns="….">
  10.             < otherheader>xxxx</otherheader>
  11.         </RequestSOAPHeader>
  12.     </soap:Header>
  13.     <soap:Body>
  14.         ……..
  15.     </soap:Body>
  16. </soap:Envelope>

安装WSE3.0版本。在VS项目中添加Microsoft.Web.Services3的引用。.

 

首先,导入有java服务端生成的wsdl文件,生成客户段代理类。

这里导入wsdl文件有两种方法:

一、VS提供的命令提示符中编译WSDL文件。

给个例子:

Wsdl /language:CS /n:mynamespace /out:myProxyClass.cs C:/myProject/wsdl/webservice.wsdl

最后一个参数是本地的绝对路径,是一个文件,也可以是一个网络路径。

二、在项目右键中添加WEB引用,输入本地的WSDL的绝对路径。

 

注意:用VS引用生成的代理类名称为Reference.cs,可以在项目目录下找到。

 

然后,修改本地生成的代理类,在最后一个using下面添加

  1. [System.Xml.Serialization.XmlTypeAttribute(Namespace = "…")]
  2. [System.Xml.Serialization.XmlRootAttribute(Namespace = "…", IsNullable = false)]
  3. public class RequestSOAPHeader : System.Web.Services.Protocols.SoapHeader
  4. {
  5.     public string otherheader;
  6. }       

System.Web.Services.Protocols.SoapHttpClientProtocol替换为Microsoft.Web.Services3.WebServicesClientProtocol

 

在代理类的构造函数上面,private bool useDefaultCredentialsSetExplicitly这行代码下面添加public RequestSOAPHeader ServiceAuthHeaderValue这行代码,注意要在类的里面,作为服务类的公共对象。

最后,找到你要调用的那个服务方法,在上面添加

[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceAuthHeaderValue")]这行代码,注意ServiceAuthHeaderValue是声明的公共成员。

如果你找不到,你可以搜索下类似[System.Web.Services.Protocols.SoapDocumentMethodAttribute("", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Bare)]的代码。对,就在这上面或下面添加。

如果你看了上面的这些还不是很理解,可以参考下面的例子(根据一个网友提供的资料整理,省略部分代码)

  1. sing System;
  2. using System.ComponentModel;
  3. using System.Diagnostics;
  4. using System.Web.Services;
  5. using System.Web.Services.Protocols;
  6. using System.Xml.Serialization;
  7. //  
  8. // 此源代码由 wsdl 自动生成, Version=2.0.50727.1432。 
  9. //  
  10. [System.Xml.Serialization.XmlTypeAttribute(Namespace = "…")] 
  11. [System.Xml.Serialization.XmlRootAttribute(Namespace = "…", IsNullable = false)] 
  12. public class RequestSOAPHeader : System.Web.Services.Protocols.SoapHeader 
  13.     public string otherheader; 
  14. }
  15. /// <remarks/> 
  16. [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl""2.0.50727.1432")]
  17. [System.Diagnostics.DebuggerStepThroughAttribute()]
  18. [System.ComponentModel.DesignerCategoryAttribute("code")]
  19. [System.Web.Services.WebServiceBindingAttribute(Name="SendMessageBinding", Namespace="http://www.xxx.com.cn")]
  20. public partial class SendMessageBinding : Microsoft.Web.Services3.WebServicesClientProtocol {
  21.     
  22.     private System.Threading.SendOrPostCallback sendMessageOperationCompleted;
  23.     
  24.     private System.Threading.SendOrPostCallback getMessageDeliveryStatusOperationCompleted;
  25.     
  26.     public RequestSOAPHeader ServiceAuthHeaderValue;
  27.     
  28.     /// <remarks/> 
  29.     public SendMessageBinding() {
  30.         this.Url = "http://www.xxx.com.cn";
  31.     }
  32.     
  33.     /// <remarks/> 
  34.     public event sendMessageCompletedEventHandler sendMessageCompleted;
  35.     
  36.     /// <remarks/> 
  37.     public event getMessageDeliveryStatusCompletedEventHandler getMessageDeliveryStatusCompleted;
  38.     
  39.     /// <remarks/> 
  40.     [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceAuthHeaderValue")]
  41.     [System.Web.Services.Protocols.SoapDocumentMethodAttribute("", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Bare)]
  42.     [return: System.Xml.Serialization.XmlElementAttribute("sendMessageResponse", Namespace="http://www.xxx.com.cn")]
  43.     public sendMessageResponse sendMessage([System.Xml.Serialization.XmlElementAttribute("sendMessage", Namespace="http://www.xxx.com.cn")] sendMessage sendMessage1) {
  44.         object[] results = this.Invoke("sendMessage"new object[] {
  45.                     sendMessage1});
  46.         return ((sendMessageResponse)(results[0]));
  47.     }
  48. ......

到这里就修改好了代理类了,注意保存备份下,不要更新代理类,否则,代理类又会还原回去了。

 

接着设置下WSE的配置,右击项目选择WSE settings 3.0…

勾选General下的Enable this project for web service enhancements

选择Policy,勾选Enable Policy,然后点Add,我这里已经添加了,没添加的时候是空的。

填写Policy的名称为ClientPolicy,在向导中,依次选择Secure a client application+username ->Specify username token in code ->None

最后生成的Policy信息如下:

然后到Security选项卡里点击Security Tokens Managers中的Add,在下拉框中选择Username Token Manager,会自动生成其他的信息,点OK保存即可。

 

看下你的app.config中有没有如下信息:

  1. <configSections>
  2.     <section name="microsoft.web.services3" type="Microsoft.Web.Services3.Configuration.WebServicesConfiguration, Microsoft.Web.Services3, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
  3.    …….
  4.     </sectionGroup>
  5.   </configSections>
  6.   <microsoft.web.services3>
  7.     <policy fileName="wse3policyCache.config" />
  8.     <security>
  9.       <securityTokenManager>
  10.         <add type="Microsoft.Web.Services3.Security.Tokens.UsernameTokenManager, Microsoft.Web.Services3, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" namespace="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" localName="UsernameToken" />
  11.       </securityTokenManager>
  12.     </security>  
  13.   </microsoft.web.services3>

wse3policyCache.config里的信息如下:

  1. <policies xmlns="http://schemas.microsoft.com/wse/2005/06/policy">
  2.   <extensions>
  3.      <extension name="requireActionHeader" type="Microsoft.Web.Services3.Design.RequireActionHeaderAssertion, Microsoft.Web.Services3, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
  4.     <extension name="usernameOverTransportSecurity" type="Microsoft.Web.Services3.Design.UsernameOverTransportAssertion, Microsoft.Web.Services3, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
  5.   </extensions>
  6.   <policy name="ClientPolicy">
  7.     <usernameOverTransportSecurity />
  8.     <requireActionHeader />
  9.      </policy>
  10. </policies>

下面是调用服务方法的关键代码:

  1. //服务对象
  2. ProxyService sendws = new ProxyService();
  3. //添加SOAP头
  4. ProxyService.RequestSOAPHeader Soapheader = new ProxyService.RequestSOAPHeader();
  5. Soapheader.otherheader=”xxx”;
  6. sendws.ServiceAuthHeaderValue = Soapheader; 
  7. //设置协议
  8. UsernameToken token = new UsernameToken("username""password", PasswordOption.SendPlainText);
  9. sendws.SetClientCredential(token);
  10. sendws.SetPolicy("ClientPolicy");
  11. sendws.Url = ".....";
  12. sendws.webmethod ();

到这里使用Fiddler截包,发现SOAP包头中的信息出现了Action, Timestamp等信息,为了得到更加灵活的SOAP头,就必须重写SoapFilter类。

 

在你的项目中添加一个类UsernameClientAssertion

  1. class UsernameClientAssertion : SecurityPolicyAssertion
  2.     {
  3.         public string UserName;
  4.         public string PassWord;
  5.         public UsernameClientAssertion(string UserName, string PassWord)
  6.         {
  7.             this.UserName = UserName;
  8.             this.PassWord = PassWord;
  9.         }
  10.         public override SoapFilter CreateClientOutputFilter(FilterCreationContext context)
  11.         {
  12.             return new ClientOutputFilter(this, context);
  13.         }
  14.         public override SoapFilter CreateClientInputFilter(FilterCreationContext context)
  15.         {
  16.             return null;
  17.         }
  18.         public override SoapFilter CreateServiceInputFilter(FilterCreationContext context)
  19.         {
  20.             return null;
  21.         }
  22.         public override SoapFilter CreateServiceOutputFilter(FilterCreationContext context)
  23.         {
  24.             return null;
  25.         }
  26. }

新建一个ClientOutputFilter

  1. class ClientOutputFilter : SoapFilter 
  2. {
  3.         private UsernameClientAssertion parentAssertion;
  4.         private FilterCreationContext filterContext;        
  5.         public ClientOutputFilter(UsernameClientAssertion parentAssertion, FilterCreationContext filterContext)
  6.         {
  7.             this.parentAssertion = parentAssertion;
  8.             this.filterContext = filterContext;
  9.         }
  10.         public override Microsoft.Web.Services3.SoapFilterResult ProcessMessage(SoapEnvelope envelope)
  11.         {
  12.             XmlElement securityElement = envelope.CreateElement("wsse""Security""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
  13.             XmlAttribute mustUnderstandAttribute = envelope.CreateAttribute(envelope.DocumentElement.Prefix,
  14.                 "mustUnderstand", envelope.DocumentElement.NamespaceURI);
  15.             mustUnderstandAttribute.Value = "true";
  16.             UsernameToken userToken = new UsernameToken(parentAssertion.UserName, parentAssertion.PassWord, PasswordOption.SendPlainText);
  17.                         
  18.             securityElement.AppendChild(userToken.GetXml(envelope));            
  19.             securityElement.FirstChild.RemoveChild(securityElement.FirstChild.FirstChild.NextSibling.NextSibling);
  20.             securityElement.FirstChild.RemoveChild(securityElement.FirstChild.FirstChild.NextSibling.NextSibling);                        
  21.             //envelope.CreateHeader().RemoveAll();
  22.             envelope.CreateHeader().PrependChild(securityElement);
  23.             envelope.CreateHeader().RemoveChild(envelope.CreateHeader().FirstChild.NextSibling.NextSibling);
  24.             envelope.CreateHeader().RemoveChild(envelope.CreateHeader().FirstChild.NextSibling.NextSibling);
  25.             envelope.CreateHeader().RemoveChild(envelope.CreateHeader().FirstChild.NextSibling.NextSibling);
  26.             envelope.CreateHeader().RemoveChild(envelope.CreateHeader().FirstChild.NextSibling.NextSibling);            
  27.             return SoapFilterResult.Continue;
  28.         }
  29. }

简单说下上面的代码,创建灵活的SOAP头就在方法public override Microsoft.Web.Services3.SoapFilterResult ProcessMessage(SoapEnvelope envelope)里,

可以看得出就是对XML的操作啦,如果调不出你要的包,就设个断点F10F10。。。

 

修改下原来的代码为:

  1. //服务对象
  2. ProxyService sendws = new ProxyService();
  3. //添加SOAP头
  4. ProxyService.RequestSOAPHeader Soapheader = new ProxyService.RequestSOAPHeader();
  5. Soapheader.otherheader=”xxx”;
  6. sendws.ServiceAuthHeaderValue = Soapheader; 
  7. //设置协议
  8. UsernameToken token = new UsernameToken("username""password", PasswordOption.SendPlainText);
  9. Policy ProvideUsernameToken = new Policy();
  10. ProvideUsernameToken.Assertions.Add(new UsernameClientAssertion("domain_user""domain_user"));
  11. UsernameTokenManager tokenm = new UsernameTokenManager();
  12. sendws.SetClientCredential(token);
  13. sendws.SetPolicy(ProvideUsernameToken);
  14. sendws.Url = "...";
  15. sendws.webmethod ();

这样就重写了SOAP头的输出部分了。

 

总结

WSE3.0只能在VS2005下才能集成在项目中,VS2008不能支持,我之前试着直接改写app.configwse3policyCache.config里的内容都失败了,觉得可能是证书的生成有问题,WSE也提供手动生成证书,但是这么多东西都用手动生成,恐怕不太容易,稍有差错就调试不出来了。

VS2008下已经使用WCF代替了WSE了,使用了绑定设置的方法,我也没有试出来,如果你试出来了,请告诉我,谢谢。

 

修订:

1.添加代理类例子 2008-10-15

2.修改标题,方便搜索的到 2008-11-15

 

原创粉丝点击