从C#直接将原始SOAP XML发送到WCF服务

lox*_*lox 15 .net c# wcf soap

我有一个WCF服务参考:

http://.../Service.svc(?WSDL)
Run Code Online (Sandbox Code Playgroud)

我有一个包含兼容SOAP信封的XML文件

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Body>
    <MyXML>
       ...
Run Code Online (Sandbox Code Playgroud)

现在,我想通过一些C#代码将这些原始数据直接发送到服务(并接收响应),而不使用Visual Studio服务引用.

这是可能的,如果是的话,怎么样?

Dar*_*rov 31

你可以使用UploadString.您需要适当地设置Content-TypeSOAPAction标头:

class Program
{
    static void Main(string[] args)
    {
        using (var client = new WebClient())
        {
            // read the raw SOAP request message from a file
            var data = File.ReadAllText("request.xml");
            // the Content-Type needs to be set to XML
            client.Headers.Add("Content-Type", "text/xml;charset=utf-8");
            // The SOAPAction header indicates which method you would like to invoke
            // and could be seen in the WSDL: <soap:operation soapAction="..." /> element
            client.Headers.Add("SOAPAction", "\"http://www.example.com/services/ISomeOperationContract/GetContract\"");
            var response = client.UploadString("http://example.com/service.svc", data);
            Console.WriteLine(response);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

我只想评论Darin的回复对我有用,除了我必须取出SOAPAction头值附加的额外引号(当然替换你的uri):

client.Headers.Add("SOAPAction", "http://www.example.com/services/ISomeOperationContract/GetContract");
Run Code Online (Sandbox Code Playgroud)