将标题添加到简单Web服务请求

人气:795 发布:2022-09-21 标签: header web-services c# .net-4.5 service-reference

问题描述

我有一个控制台应用程序,我简单地通过点击添加Web引用并使用添加服务引用,然后将我的.Config文件更改为:

 <?xml version =1.0encoding =utf-8?> <配置> < system.serviceModel> < bindings> < basicHttpBinding> < binding name =FServiceSoapBinding/> < / basicHttpBinding> < / bindings> < client>   ; < / client> < /system.serviceModel> < / configuration>   

所以,每件事情都很好,看起来我可以成功地使用服务,但服务文档说

 < soapenv:&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&> Envelope xmlns:soapenv =http://schemas.xmlsoap.org/soap/envelope/ xmlns:web =http://namespace.com/> < soapenv:Header> <帐户> <使用者名称>使用者< /使用者名称> <密码>密码< /密码> < /帐户> < / soapenv:Header> < soapenv:Body> < web:oneofservicemethods> <项目> < item> ...< / item> < / item> < / web:oneofservicemethods> < / soapenv:Body> < / soapenv:Envelope>   

那么如何将用户名和密码添加到标题?任何建议吗?

解决方案

如果我理解正确,您希望在请求头上设置用户名和密码。您可以通过使用 WCF可扩展性 - 消息检查器 IClientMessageInspector.BeforeSendRequest 来实现。

创建一个实现 IClientMessageInspector 的类。在BeforeSendRequest方法中,将自定义标题添加到传出消息。

请参阅这个,这和此

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?

解决方案

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

187