Wednesday, October 31, 2012

Add header variables to WCF service request using ChannelFactory

This is a way to add a specific soap header to a service request:

using (ChannelFactory factory = new ChannelFactory<ITest>(new BasicHttpBinding(BasicHttpSecurityMode.None), http://localhost/service.svc)){
 
  using(ITest proxy = factory.CreateChannel())  {
    //Sets up OperationContext so that the header can be added to soap request
    using (OperationContextScope contextScope = new OperationContextScope(proxy))
    { 
      var appHeader = new MessageHeader<string>("appID1");
          string HeaderAppString = "application";          

      OperationContext.Current.OutgoingMessageHeaders.Add(appHeader.GetUntypedHeader  (HeaderAppString, ns));
      TestCandidateResponse retVal = proxy.Print(details);   
     }
  }
}   

This action will add an "application" node in the soap header packet with the value of appID1 as seen below:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header>
    <application xmlns="ns"> appID1 </application>
  <s:Header>

<s:Body>

  .........
</s:Body>

</s:Envelope>







No comments: