Add Header to the Simple Web Service Request

Saeid picture Saeid · Nov 7, 2012 · Viewed 7.8k times · Source

I have a Console application, I add a Web reference simply by write click and use "Add Service Reference", then my .Config file changed to:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="FServiceSoapBinding" />
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://ServiceAdd/FService" binding="basicHttpBinding"
                bindingConfiguration="FServiceSoapBinding" contract="MyReference.MService_"
                name="FServicePort" />
        </client>
    </system.serviceModel>
</configuration>

So, every thing is fine and it seems I can use the service successfully, but the service documentation said I need set username and password on the header of the requests, and this is the example of the documentation:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:web="http://namespace.com/">
  <soapenv:Header>
    <Account>
      <username>user</username>
      <password>password</password>
    </Account>
  </soapenv:Header>
  <soapenv:Body>
    <web:oneofservicemethods>
      <items>
        <item>...</item>
      </items>
    </web:oneofservicemethods>
  </soapenv:Body>
</soapenv:Envelope>

So How can I add username and password to the header? any suggestion?

Answer

Saeid picture Saeid · Nov 10, 2012

For add static header simply can add in .config file endpoint part so change endpoint to:

<client>
    <endpoint address="http://ServiceAdd/FService" binding="basicHttpBinding"
     bindingConfiguration="FServiceSoapBinding" contract="MyReference.MService_"
     name="FServicePort" >
        <headers>
            <Account>
                <username>user</username>
                <password>password</password>
            </Account>
        </headers>
    </endpoint>
</client>