如何在WCF中发送已构造的SOAP消息

时间:2011-06-07 12:14:36

标签: wcf serialization soap deserialization

我在客户端的字符串中有一条SOAP消息

string requestMessageString = "<soapenv:Envelope 
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" 
xmlns:inf="http://www.informatica.com/" 
xmlns:wsdl="http://www.informatica.com/wsdl/"> 
    <soapenv:Header> 
       <inf:Security> 
          <UsernameToken> 
             <Username>john</Username> 
             <Password>jhgfsdjgfj</Password> 
          </UsernameToken> 
       </inf:Security> 
    </soapenv:Header> 
    <soapenv:Body> 
       <wsdl:doClient_ws_IbankRequest> 
          <wsdl:doClient_ws_IbankRequestElement> 
             <!--Optional:--> 
             <wsdl:Client_No>00460590</wsdl:Client_No> 
          </wsdl:doClient_ws_IbankRequestElement> 
       </wsdl:doClient_ws_IbankRequest> 
    </soapenv:Body> 
</soapenv:Envelope>"

我正在发送这样的消息

Message requestMsg = Message.CreateMessage(MessageVersion.Soap11, "http://tempuri.org/IService1/IbankClientOperation", requestMessageString );

            Message responseMsg = null;

            BasicHttpBinding binding = new BasicHttpBinding();
            IChannelFactory<IRequestChannel> channelFactory = binding.BuildChannelFactory<IRequestChannel>();
            channelFactory.Open();

            EndpointAddress address = new EndpointAddress(this.Url);
            IRequestChannel channel = channelFactory.CreateChannel(address);
            channel.Open();

            responseMsg = channel.Request(requestMsg);

但问题是通过线路发送的实际消息在SOAP消息中有一条SOAP消息...... 我想以某种方式将我的RAW消息转换为SOAP结构

3 个答案:

答案 0 :(得分:0)

您不能将Soap11用作消息版本,也不能使用BasicHttpBinding。尝试:

Message requestMsg = Message.CreateMessage(MessageVersion.None, "http://tempuri.org/IService1/IbankClientOperation", requestMessageString );

CustomBinding binding = new CustomBinding(new HttpTransportBindingElement());
IChannelFactory<IRequestChannel> channelFactory = binding.BuildChannelFactory<IRequestChannel>();
channelFactory.Open();

但无论如何,如果您有SOAP请求,为什么不使用WebClientHttpWebRequest将请求发布到服务器?

答案 1 :(得分:0)

我从这个问题得到了答案 wcf soap message deserialization error

答案 2 :(得分:0)

您可以将SOAP消息转换(反序列化)为服务所需的对象。这是一个对我有用的草图:

var invoice = Deserialize<Invoice>(text);
var result = service.SubmitInvoice(invoice);

反序列化是这样的:

private T Deserialize<T>(string text)
{
  T obj;
  var serializer = new DataContractSerializer(typeof(T));
  using (var ms = new MemoryStream(Encoding.Default.GetBytes(text)))
  {
      obj = (T)serializer.ReadObject(ms);
  }  
  return obj;
}

由于SOAP是XML,因此您可以在反序列化之前轻松调整其结构(例如删除或更改命名空间)。