C#.NET中HTTP上的SOAP对象

Aar*_*ong 12 .net c# soap http-post envelope

我正在尝试在C#.NET中编写SOAP消息(包括头文件)以使用HTTP post发送到URL.我想将其发送到的URL不是Web服务,它只接收SOAP消息以最终从中提取信息.关于如何做到这一点的任何想法?

Ale*_*ini 15

首先,您需要创建有效的XML.我使用Linq to XML来实现这一点,如下所示:

XNamespace soapenv = "http://schemas.xmlsoap.org/soap/envelope/";
var document = new XDocument(
               new XDeclaration("1.0", "utf-8", String.Empty),
               new XElement(soapenv + "Envelope",
                   new XAttribute(XNamespace.Xmlns + "soapenv", soapenv),
                   new XElement(soapenv + "Header",
                       new XElement(soapenv + "AnyOptionalHeader",
                           new XAttribute("AnyOptionalAttribute", "false"),
                       )
                   ),
                   new XElement(soapenv + "Body",
                       new XElement(soapenv + "MyMethodName",
                            new XAttribute("AnyAttributeOrElement", "Whatever")
                       )
                   )
                );
Run Code Online (Sandbox Code Playgroud)

然后我发送它(编辑:XDocument.ToString()在这里添加.)

            var req = WebRequest.Create(uri);
            req.Timeout = 300000;  //timeout
            req.Method = "POST";
            req.ContentType = "text/xml;charset=UTF-8";

            using (var writer = new StreamWriter(req.GetRequestStream()))
            {
                writer.WriteLine(document.ToString());
                writer.Close();
            }
Run Code Online (Sandbox Code Playgroud)

如果我必须阅读一些回复,我这样做(这是以上代码的后续):

            using (var rsp = req.GetResponse())
            {
                req.GetRequestStream().Close();
                if (rsp != null)
                {
                    using (var answerReader = 
                                new StreamReader(rsp.GetResponseStream()))
                    {
                        var readString = answerReader.ReadToEnd();
                        //do whatever you want with it
                    }
                }
            }
Run Code Online (Sandbox Code Playgroud)