首页 > 解决方案 > 如何使用连接服务将自定义标头添加到传出 SOAP 有效负载?

问题描述

我需要使用 HTTPS 端点向我的项目中发送到其中一个连接服务的每个有效负载添加一个自定义标头。该自定义标头将用作接收者的身份验证。我怎样才能做到这一点?

我试过使用System.ServiceModel.Channels.MessageHeaderAddressHeader没有运气。使用 SoapUI,向请求中添加自定义标头可以正常工作。

这种身份验证方法对接收方来说是新的。以及 HTTPS 端点。在以前的请求中,我使用Basic Http Authentication的是用户名和密码。因此,我对此进行了一些更改以支持 HTTPS 绑定代码:

BasicHttpsBinding basicAuthBinding = new BasicHttpsBinding(BasicHttpsSecurityMode.Transport);
basicAuthBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;

EndpointAddress basicAuthEndpoint = new EndpointAddress("https://whatever");
MyConnectedService.MyOperationClient client = new MyConnectedService.MyOperationClient(basicAuthBinding, basicAuthEndpoint);

client.ClientCredentials.UserName.UserName = "user";         
client.ClientCredentials.UserName.Password = "pass";

client.send(payload);

我相信在这里的某个地方我需要添加自定义标题。

使用此代码,我得到了预期的HTTP 401 - Unauthorized.

帮助表示赞赏。

先感谢您。

标签: c#asp.netwcf

解决方案


如果您接受静态自定义标头,您可以尝试 web.config(app.config)。

 <endpoint address="http://ws-wuxipc-5077:4000/calculator" binding="basicHttpBinding"
  contract="ServiceInterface.CustomHeader" name="header">
  <headers>
    <Security xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" >
      <wsse:UsernameToken xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
        xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
        <wsse:Username>
        </wsse:Username>
        <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">monMonDePasse</wsse:Password>
        <wsse:Nonce>sdsdsdlojhfdsdM5Nw==</wsse:Nonce>
        <wsu:Created>2019-01-21T6:17:34Z</wsu:Created>
      </wsse:UsernameToken>
    </Security>
  </headers>
</endpoint>

推荐阅读