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

标签 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>
   ...

我可以添加如下所示的soap标题
<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>

我无法做的是添加包装“UsernameToken”的“Security”元素,就像在第一个示例中一样。任何帮助,将不胜感激。

最佳答案

此链接 adding soap header为我工作。我正在调用一个 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;
    }
}

然后在生成的代理类中,在调用服务的方法上,按照 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();
}

关于c# - 在 C# 中为 Web 服务调用添加自定义 SOAPHeader,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18980689/

相关文章:

java - 如何将 xmlbean 文档元素添加到soap header spring-ws

c# - 如何在 C# 中忽略用户响应中的大小写?

c# - 饮食异常(exception)

c# - 如何获取 XML 格式的 SOAP header ?

java - 将 soap header 身份验证添加到 wsdl2java 生成的代码

c# - UI的并行生成

c# - 如何根据类型忽略属性

c# - 是否有在基于 DDD 的分层架构中的模型和数据访问层之间使用 LINQ 的建议模式

c# - 如何向我的 SOAP 添加 Basic Auth Header?