【问题标题】:Error when sending SOAP Request in C# Console Application在 C# 控制台应用程序中发送 SOAP 请求时出错
【发布时间】:2017-02-23 14:52:03
【问题描述】:

我正在尝试在 C# 控制台应用程序中发布请求,但出现此错误。该请求在 SOAPUI 中运行,没有 WSDL 文件,因此我必须直接在代码中加载 XML(我高度怀疑这是错误的来源)。

控制台应用程序的输出如下:

正在运行的 SOAPUI 请求如下:

这是我用来发送此 SOAP 请求的 C# 控制台应用程序。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace IMSPostpaidtoPrepaid
{
    class Program
    {
        static void Main(string[] args)
        {
            Program obj = new Program();
            obj.createSOAPWebRequest();
        }

        //Create the method that returns the HttpWebRequest
        public void createSOAPWebRequest()
        {

            //Making the Web Request
            HttpWebRequest Req = (HttpWebRequest)WebRequest.Create(@"http://127.1.1.0:9090/spg");

            //Content Type
            Req.ContentType = "text/xml;charset=utf-8";
            Req.Accept = "text/xml";

            //HTTP Method
            Req.Method = "POST";

            //SOAP Action
            Req.Headers.Add("SOAPAction", "\"SOAPAction:urn#LstSbr\"");

            NetworkCredential creds = new NetworkCredential("username", "pass");
            Req.Credentials = creds;

            Req.Headers.Add("MessageID", "1"); //Adding the MessageID in the header

            string DN = "+26342720450";
            string DOMAIN = "ims.telone.co.zw";

            //Build the XML
            string xmlRequest = String.Concat(
                "<?xml version=\"1.0\" encoding=\"utf-8\"?>",
                "<soap:Envelope",
                "      xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"",
                "      xmlns:m=\"http://www.huawei.com/SPG\"",
                "      xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"",
                "      xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">",
                "  <soap:Body>",
                "<m:LstSbr xmlns=\"urn#LstSbr\">",
                "   < m:DN >", DN, "</ m:DN>",
                "   < m:DOMAIN >", DOMAIN, "</ m:DOMAIN>",
                "    </m:LstSbr>",
                "  </soap:Body>",
                "</soap:Envelope>");


            //Pull Request into UTF-8 Byte Array
            byte[] reqBytes = new UTF8Encoding().GetBytes(xmlRequest);

            //Set the content length
            Req.ContentLength = reqBytes.Length;

            //Write the XML to Request Stream
            try
            {
                using (Stream reqStream = Req.GetRequestStream())
                {
                    reqStream.Write(reqBytes, 0, reqBytes.Length);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception of type " + ex.GetType().Name + " " + ex.Message );
                Console.ReadLine();
                throw;
            }

            //Headers and Content are set, lets call the service
            HttpWebResponse resp = (HttpWebResponse)Req.GetResponse();

            string xmlResponse = null;

            using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
            {
                xmlResponse = sr.ReadToEnd();
            }
            Console.WriteLine(xmlResponse);
            Console.ReadLine();

        }

    }
}

【问题讨论】:

    标签: c# xml soap console-application soapui


    【解决方案1】:

    这是我用来发布到网络服务的基本方法。

    static XNamespace soapNs = "http://schemas.xmlsoap.org/soap/envelope/";
    static XNamespace topNs = "Company.WebService";
    
    private System.Net.HttpWebResponse ExecutePost(string webserviceUrl, string soapAction, string postData) {
        var webReq = (HttpWebRequest)WebRequest.Create(webserviceUrl);
        webReq.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;  
        webReq.ContentType = "text/xml;charset=UTF-8";  
        webReq.UserAgent = "Opera/12.02 (Android 4.1; Linux; Opera Mobi/ADR-1111101157; U; en-US) Presto/2.9.201 Version/12.02";
        webReq.Referer = "http://www.company.com";  
        webReq.Headers.Add("SOAPAction", soapAction);
        webReq.Method = "POST";
    
        var encoded = Encoding.UTF8.GetBytes(postData);
        webReq.ContentLength = encoded.Length;
        var dataStream = webReq.GetRequestStream();
        dataStream.Write(encoded, 0, encoded.Length);
        dataStream.Close();
    
        System.Net.WebResponse response;
        try { response = webReq.GetResponse(); }
        catch { 
            ("Unable to post:\n" + postData).Dump();
            throw;
        }
    
        return response as System.Net.HttpWebResponse;
    }
    

    然后我可以围绕它构建任何我想要的东西来做我需要的事情。例如,这是我将如何使用它。

    private void CreateTransaction(string webServiceUrl, string ticket, double costPerUnit) {
        string soapAction = "Company.WebService/ICompanyWebService/CreatePurchaseTransaction";
        var soapEnvelope = new XElement(soapNs + "Envelope",
                            new XAttribute(XNamespace.Xmlns + "soapenv", "http://schemas.xmlsoap.org/soap/envelope/"),
                            new XAttribute(XNamespace.Xmlns + "top", "Company.WebService"),                     
                        new XElement(soapNs + "Body", 
                            new XElement(topNs + "CreatePurchaseTransaction", 
                                new XElement(topNs + "command", 
                                    new XElement(topNs + "BillTransaction", "true"),
                                    new XElement(topNs + "BillingComments", "Created By C# Code"),
                                    new XElement(topNs + "Department", "Development"),
                                    new XElement(topNs + "LineItems", GetManualPurchaseLineItems(topNs, costPerUnit)),                                  
                                    new XElement(topNs + "Surcharge", "42.21"),
                                    new XElement(topNs + "Tax", "true"),
                                    new XElement(topNs + "TransactionDate", DateTime.Now.ToString("yyyy-MM-dd"))
                        ))));
    
        var webResp = ExecutePost(webServiceUrl, soapAction, soapEnvelope.ToString());  
        if (webResp.StatusCode != HttpStatusCode.OK) 
            throw new Exception("Unable To Create The Transaction");
    
        var sr = new StreamReader(webResp.GetResponseStream());
        var xDoc = XDocument.Parse(sr.ReadToEnd());
        var result = xDoc.Descendants(topNs + "ResultType").Single();
        if (result.Value.Equals("Success", StringComparison.CurrentCultureIgnoreCase) == false)
            throw new Exception("Unable to post the purchase transaction.  Look in the xDoc for more details.");
    }
    
    private IEnumerable<XElement> GetManualPurchaseLineItems(XNamespace topNs, double costPerUnit) {
        var lineItems = new List<XElement>();
    
        lineItems.Add(new XElement(topNs + "PurchaseLineItem",
                            new XElement(topNs + "Count", "5"),
                            new XElement(topNs + "ExpenseClass", "Tech Time"),
                            new XElement(topNs + "ItemName", "Brushing and Flossing"),
                            new XElement(topNs + "Location", "Your House"),
                            new XElement(topNs + "UnitCost", costPerUnit.ToString("#.00"))));
    
        return lineItems;
    }
    

    您需要将其调整到您的控制台应用程序中,但这对您有帮助吗?

    【讨论】:

    • 看一看
    • 嘿@nktsamba,你有机会解决吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-10
    • 2011-03-27
    • 1970-01-01
    • 2011-10-31
    • 2011-05-05
    • 1970-01-01
    • 2011-02-28
    相关资源
    最近更新 更多