在C#控制台应用程序中发送SOAP请求时出错

时间:2017-02-23 14:52:04

标签: c# xml soap console-application soapui

我正在尝试在C#控制台应用程序中发布请求,但我收到此错误。该请求在SOAPUI中工作,没有WSDL文件,所以我必须直接在代码中加载XML(我非常怀疑这是错误的来源)。

控制台应用程序的输出如下:Error Message On Console

正在运行的SOAPUI请求如下: enter image description here

以下是我用来发送此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();

        }

    }
}

1 个答案:

答案 0 :(得分:0)

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

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;
}

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