在C#控制台中使用Soap服务进行身份验证

时间:2013-06-25 18:44:02

标签: c# soap console wsdl soap-client

我正在尝试从C#中的控制台连接到soap服务(wsdl)。 我的代码相当简单,我将wsdl作为服务引用添加到项目中,并且按预期创建了代理类(?)。

该服务使用每条消息的身份验证密钥,我找不到任何地方将其添加到soap标头。 作为参考,这是我在main方法中运行的代码:

Api.Servicereference1.PortClient object = new Api.Servicereference1.PortClient();                        
object.testmethod();

此作品的输出如下:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <testmethod xmlns="http://wsdlserver.com/soap"/>
    </s:Body>
</s:Envelope>

但是,我想要实现的是通过身份验证发送的以下消息:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Header>
        <s:auth>key</s:auth>
    </s:Header>
    <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">        
        <testmethod xmlns="http://wsdlserver.com/soap"/>
    </s:Body>
</s:Envelope>

任何人都可以帮我找到正确的方向,关于如何将这个自定义标题添加到我的邮件中? 感谢。

2 个答案:

答案 0 :(得分:1)

有关如何向WCF客户端代理添加自定义标头的文章:

Adding custom headers to every WCF call - a solution

答案 1 :(得分:0)

好的,感谢您的输入,我做了一些阅读,并认为如果我用 OperationContextScope 包围我的消息,我可以随意添加标题。 我将代码更改为:

Api.Servicereference1.PortClient object = new Api.Servicereference1.PortClient();
using ( OperationContextScope scope = new OperationContextScope(object.InnerChannel))
{
     MessageHeader soapheader = MessageHEader.CreateHeader("name","ns",payload);
     OperationContext.Current.OutgoingMessageHeaders.Add(soapheader);
     object.testmethod();
}

此处解释 MessageHeader.CreateHeader()中的参数MessageHeader.CreateHeader Method (String, String, Object) from msdn.microsoft.com

虽然这个解决方案需要我手动为我的所有消息添加一个OperationContext,但它解决了我自定义soapheader的问题。