如何使用自定义标头使用SOAP服务

时间:2019-04-05 01:22:46

标签: c# web-services soap

我需要使用供应商提供的SOAP服务。我已经在Visual Studio中使用WSDL创建了代理服务,实例化了客户端类,称为操作方法,并获得了响应。一切正常,直到供应商在soap envelop标头中要求访问令牌。我可以在另一个服务调用中从他们那里获取访​​问令牌,但是如何将其添加到soap请求标头中?
这是供应商头文件的结构:
 

<SOAP:Header> 
    <SOAP-SEC:Security SOAP:mustUnderstand="1">
      <wsse:SecuredKey ValueType="..." EncodingType="wsse:Base64Binary">
        {ACCESS TOKEN}
      </wsse:SecuredKey>
    </SOAP-Sec:Security>
  </SOAP:Header>
  <SOAP:Body/>
</SOAP:Envelop>

1 个答案:

答案 0 :(得分:0)

到目前为止,最简单的方法是在模板中使用字符串替换。将消息存储为项目中的资源(例如,存储在Resources.resx中或另存为文件,并将set build action设置为嵌入式资源)。模板如下所示:

<SOAP:Header> 
    <SOAP-SEC:Security SOAP:mustUnderstand="1">
      <wsse:SecuredKey ValueType="..." EncodingType="wsse:Base64Binary">
        {ACCESS TOKEN}
      </wsse:SecuredKey>
    </SOAP-Sec:Security>
  </SOAP:Header>
  <SOAP:Body/>
</SOAP:Envelop>

从您的资源中以字符串形式加载模板,然后调用Web服务以获得访问令牌,并用实际的访问令牌替换 {ACCESS TOKEN} 。您现在可以使用以下方式发送肥皂消息System.Net.Http.HttpClientSystem.Net.WebClient

使用WebClient

的示例
using (var client = new WebClient())
{
    var result = client.UploadString("http://your.target/endpoint", yourXDocument.ToString(SaveOptions.DisableFormatting));                
    return XDocument.Parse(result);
}

SaveOptions.DisableFormatting不会尝试漂亮地打印XDocument,这在将签名的xml文档与WS-Security一起使用时可能很重要。不知道这是否适用于您的情况。