Search code examples
c#web-servicesheader.net-4.5service-reference

Add Header to the Simple Web Service Request


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?


Solution

  • If i understand correctly, you want to set username and password on the header of the requests. You can achieve by using WCF Extensibility – Message Inspectors with IClientMessageInspector.BeforeSendRequest.

    Create a class that implements IClientMessageInspector. In the BeforeSendRequest method, add your custom header to the outgoing message.

    Please see this , this and this