生成SOAP标头WCF

时间:2016-12-01 22:59:01

标签: c# web-services wcf soap

我想生成一个soap标头,以便我可以访问客户端Web服务。该服务受WS-Security保护,我需要添加以下标头:

<soapenv:Header>
    <wsse:Security 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:UsernameToken wsu:Id="UsernameToken-A1246F3623454D79AA14805153047445">
        <wsse:Username>Usuario</wsse:Username>
        <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">oU1uQxxyrF5wxxx5B+P/Y9uFW/M3DNEc=</wsse:Password>
        <wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">52sq2ilGc+9xxxxxxLBRDQ==</wsse:Nonce>
        <wsu:Created>2016-11-30T14:15:04.744Z</wsu:Created>
    </wsse:UsernameToken>
    </wsse:Security>
</soapenv:Header>

我在通过WCF配置之前已经生成了其他类型的标头,但我正在努力解决这个问题。

1 个答案:

答案 0 :(得分:0)

以下WCF代码将生成类似的SOAP Header,并且收件人可以阅读该消息。

const string apiUrl = "https://somewebservices.com", 
    apiUserName = "username", 
    apiPassword = "password";

var endpointAddress = new EndpointAddress(new Uri(apiUrl));

var securityElement = SecurityBindingElement.CreateUserNameOverTransportBindingElement();
securityElement.AllowInsecureTransport = false;
securityElement.EnableUnsecuredResponse = true;
securityElement.IncludeTimestamp = false;
var encodingElement = new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8);
var transportElement = new HttpsTransportBindingElement();
var binding = new CustomBinding(securityElement, encodingElement, transportElement);

// Then assign username and password based on the proxy. For example -
var service = new SomeProxy(binding, endpointAddress);
service.ClientCredentials.UserName.UserName = apiUserName;
service.ClientCredentials.UserName.Password = apiPassword;

结果

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
  <s:Header>
    <VsDebuggerCausalityData xmlns="http://schemas.microsoft.com/vstudio/diagnostics/servicemodelsink">XXX</VsDebuggerCausalityData>
    <o:Security s:mustUnderstand="1" xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
      <o:UsernameToken u:Id="XXX">
        <o:Username>XXX</o:Username>
        <o:Password>XXX</o:Password>
      </o:UsernameToken>
    </o:Security>
  </s:Header>
  <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    ...
  </s:Body>
</s:Envelope>