mercredi 4 mars 2015

Customize SOAP header in .Net framework ( VB.Net code )

Last week, someone ask on twitter if someone can help with VB.Net code for SOAP.

The demand was how to customize SOAP header to add new fields.
 The result was something like below

<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://a.com/">
<soap:Header   xmlns:soapHeader="http://a.com/Header">
<soapHeader:shopId>83486117>/soapHeader:shopId>
<soapHeader:requestId>ba45b5e9-db3f-4ff7-8766-98a5099d6a8b>
<soapHeader:timestamp>2015-02-25T21:54:18Z>/soapHeader:timestamp>
<soapHeader:mode>TEST<soapHeader:mode>
<soapHeader:authToken>gZ+zva7ZWhUvZK43v8vS8Jwf2ozb5PXN/O9LwyVUKZ8= </soapHeader:authToken> 
</soap:Header> 
<soap:Body>
<a:findPayments>
</a:findPayments>
</soap:Body> 
</soap:Envelope>


 By default, .Net framework access Web Services using a Service Reference to create a Web Service proxy from a WSDL description.
But the default object does not provide a direct way to customize the header except username, password and authtoken.

After a lot of research on Technet, forums and so on... I find the solution.

 Add the following import in the code

Imports System.ServiceModel
Imports System.ServiceModel.Channels


Create a Service Reference for creating the proxy ( called service below ).

Dim service As Service.PaymentAPIClient = New Service.PaymentAPIClient()



' Add a namespace ( mandatory in my case )
Dim ns As String = "http://a.com/Header"


' create a contect object. It uses to customize the InnerChannel which define the behaviour of the outbound request ( https://msdn.microsoft.com/fr-fr/library/ms553832%28v=vs.110%29.aspx )
Dim context = New OperationContextScope(service.InnerChannel())



' create a new Header for each field
Dim msgHeader1 = MessageHeader.CreateHeader("shopId", ns, xxxx)

[...]

' add header to "normal header"
 OperationContext.Current.OutgoingMessageHeaders.Add(msgHeader1)


To check the SOAP message, use a tool like Fiddler ( http://www.telerik.com/fiddler ) that will display the SOAP message when debugging.

Aucun commentaire:

Enregistrer un commentaire