Adding a custom SOAP header using c#/ASP.NET

James Hull picture James Hull · Sep 22, 2009 · Viewed 28k times · Source

I am trying to use a traffic web service. An example of the SOAP request is given below.

I have created a proxy class in c# using Wsdl.exe from the WSDL structure.

What I think I need to do now in somehow insert the 'authenticate' SOAP header into the SOAP structure for the method call. I'm unsure how to add the header to the service method call?

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:ns1="http://www.inteleacst.com.au/wsdl"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
  <SOAP-ENV:Header>
    <ns1:authenticate>
      <SOAP-ENC:Struct>
        <username>username</username>
        <password>password</password>
      </SOAP-ENC:Struct>
    </ns1:authenticate>
  </SOAP-ENV:Header>
  <SOAP-ENV:Body>
    <ns1:getAllTraffic>
      <States SOAP-ENC:arrayType="xsd:string[3]" xsi:type="ns1:State_Arr">
        <item xsi:type="xsd:string">VIC</item>
        <item xsi:type="xsd:string">NSW</item>
        <item xsi:type="xsd:string">NT</item>
      </States>
      <EventCodes SOAP-ENC:arrayType="xsd:int[1]" xsi:type="ns1:EventCode_arr">
        <item xsi:type="xsd:int">802</item>
      </EventCodes>
    </ns1:getAllTraffic>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

Here is the code in the proxy class for calling the web service method.

[System.Web.Services.Protocols.SoapRpcMethodAttribute("http://webservice.intelecast.com.au/traffic/PublicSoap/server.php#getAllTraffic", RequestNamespace="http://webservice.intelecast.com.au/traffic/PublicSoap/server.php", ResponseNamespace="http://webservice.intelecast.com.au/traffic/PublicSoap/server.php")]
        [return: System.Xml.Serialization.SoapElementAttribute("return")]
        public TrafficInfo[] getAllTraffic(string[] States, int[] EventCodes) {
            object[] results = this.Invoke("getAllTraffic", new object[] {
                        States,
                        EventCodes});
            return ((TrafficInfo[])(results[0]));
        }

Answer

James Hull picture James Hull · Sep 23, 2009

Searching the web I found a forum post about a very similar problem and a good solution. Available here - forums.asp.net/t/1137408.aspx