在C#中为Web服务调用添加自定义SOAPHeader

use*_*857 10 c# soapheader

我想在调用Web服务之前在c#中添加自定义soap头信息.我正在使用SOAP Header类来完成这项工作.我可以部分地这样做但不完全按我需要的方式完成.这是我需要肥皂头看起来像

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <soap:Header>
      <Security xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
      <UsernameToken>
         <Username>USERID</Username>
         <Password>PASSWORD</Password>
        </UsernameToken>    
      </Security>
   </soap:Header>
   <soap:Body>
   ...
Run Code Online (Sandbox Code Playgroud)

我可以添加soap header如下

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <soap:Header>
      <UsernameToken xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
         <Username>UserID</Username>
         <Password>Test</Password>
      </UsernameToken>
   </soap:Header>
   <soap:Body>
Run Code Online (Sandbox Code Playgroud)

我无法做的是添加包含"UsernameToken"的"Security"元素,如第一个示例中所示.任何帮助,将不胜感激.

PBM*_*eIt 2

这个添加肥皂头的链接对我有用。我正在调用一个不是我编写且无法控制的 SOAP 1.1 服务。我使用 VS 2012 并将该服务添加为我的项目中的 Web 参考。希望这可以帮助

我按照 J. Dudgeon 帖子中的步骤 1-5 进行操作,直至线程底部。

这是一些示例代码(这将位于单独的 .cs 文件中):

namespace SAME_NAMESPACE_AS_PROXY_CLASS
{
    // This is needed since the web service must have the username and pwd passed in a custom SOAP header, apparently
    public partial class MyService : System.Web.Services.Protocols.SoapHttpClientProtocol
    {
        public Creds credHeader;  // will hold the creds that are passed in the SOAP Header
    }

    [XmlRoot(Namespace = "http://cnn.com/xy")]  // your service's namespace goes in quotes
    public class Creds : SoapHeader
    {
        public string Username;
        public string Password;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在生成的代理类中,在调用服务的方法上,按照 J Dudgeon 的步骤 4 添加此属性:[SoapHeader("credHeader", Direction = SoapHeaderDirection.In)]

最后,这是对生成的代理方法的调用,其标头为:

using (MyService client = new MyService())
{
    client.credHeader = new Creds();
    client.credHeader.Username = "username";
    client.credHeader.Password = "pwd";
    rResponse = client.MyProxyMethodHere();
}
Run Code Online (Sandbox Code Playgroud)