添加自定义SoapClient头部

4

我是一名完全不懂C#的新手,已经尝试了几个小时但没有成功...

我需要构建一个SoapClient来在C#上使用...我一直在尝试将现有的php客户端移植到C#上。

基本上:我需要发送一个包含用户和密码的Soap头部请求,这是应该发送的xml示例。

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://webservices.paymentmanager.mycheck.com">
    <soapenv:Header xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
        <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
            <wsse:UsernameToken>
                <wsse:Username>test</wsse:Username>
                <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">pass</wsse:Password>
            </wsse:UsernameToken>
        </wsse:Security>
    </soapenv:Header>
    <SOAP-ENV:Body>
        <ns1:testws>
            <ns1:x>1</ns1:x>
        </ns1:testws>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

我使用Visual Studio的“添加服务引用”功能。该服务在使用php时表现出色,但在C#中却不起作用。

namespace ConsoleApplication1
{
    class Program
    {
        const String VENDOR_ID = "8723";
        const String VENDOR_PASS = "test";
        const String VENDOR_USER = "pass";
        static void Main(string[] args)
        {
            try
            {
                PaymentManager.PaymentManagerPortTypeClient test = new PaymentManager.PaymentManagerPortTypeClient();
                int num = test.testws(5);
                Console.WriteLine(num);
            }
            catch( Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
    }

}

显然,我不知道如何实现Soap头部,因此它会抛出一个“缺少SOAP头部”异常(这是从WebService接收到的)。
3个回答

4
我遇到了同样的问题。 我没有找到解决方案。最终,我不得不创建整个SOAP消息,并通过HTTPWebRequest发送它。
这里查看。

0

如果我得到了你的答案,那么修改服务实现是必要的,对吗?如果你没有访问服务的权限怎么办? - Alberto De Caro
@ADC 你是指服务器端吗?不,这个例子只是描述了如何创建一个SOAP调用(客户端)。 - Anas
我不同意。建议的解决方案说明:“为了强制使用我们的新SOAP头,我们需要在方法中添加以下属性:[...]”。因此,似乎必须修改服务。 - Alberto De Caro
我们需要添加SOAP头以进行SoapClient身份验证。 - cat916
@AlbertoDeCaro 不,你需要在相应的Web服务客户端存根中,将 [SoapHeader 注释添加到客户端的 [WebMethod 注释方法中。 - rustyx

-1
        XmlDocument ReqDoc = new XmlDocument();
        XmlDocument doc = new XmlDocument();
            // request message
        ReqDoc.Load(@"D:\104Resqurst.xml");
           //adding soap headder 
        XmlElement root = (XmlElement)doc.AppendChild(doc.CreateElement("soapenv", "Envelope", "http://www.w3.org/2001/XMLSchema-instance"));
        root.SetAttribute("xmlns", "http://mark.com/services/contracts");
        XmlElement header = (XmlElement)root.AppendChild(doc.CreateElement("soapenv", "Header", "http://www.w3.org/2001/XMLSchema-instance"));
        XmlElement body = (XmlElement)root.AppendChild(doc.CreateElement("soapenv", "Body", "http://www.w3.org/2001/XMLSchema-instance"));
       //assigning the request document to soap header doc
        doc.GetElementsByTagName("soapenv:Body")[0].InnerXml = ReqDoc.OuterXml;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接