Add Header to the Simple Web Service Request

让人想犯罪 __ 提交于 2019-12-01 08:25:36

问题


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?


回答1:


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




回答2:


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>


来源:https://stackoverflow.com/questions/13266468/add-header-to-the-simple-web-service-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!