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

在C#控制台应用程序中发送SOAP请求时出错,c#,xml,soap,console-application,soapui,C#,Xml,Soap,Console Application,Soapui,我试图在一个C#控制台应用程序中发布一个请求,我收到了这个错误。请求在SOAPUI中工作,没有WSDL文件,因此我必须直接在代码中加载XML(我高度怀疑这就是错误的来源) 控制台应用程序上的输出如下: 正在工作的SOAPUI请求如下所示: 这是我用来发送SOAP请求的C#控制台应用程序 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; usi

我试图在一个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();

        }

    }
}
使用系统;
使用System.Collections.Generic;
使用System.IO;
使用System.Linq;
Net系统;
使用系统文本;
使用System.Threading.Tasks;
使用System.Xml;
名称空间IMSPostPaidTopRestored
{
班级计划
{
静态void Main(字符串[]参数)
{
Program obj=新程序();
obj.createSOAPWebRequest();
}
//创建返回HttpWebRequest的方法
public void createSOAPWebRequest()
{
//发出Web请求
HttpWebRequest Req=(HttpWebRequest)WebRequest.Create(@)http://127.1.1.0:9090/spg");
//内容类型
Req.ContentType=“text/xml;charset=utf-8”;
Req.Accept=“text/xml”;
//HTTP方法
请求方法=“POST”;
//肥皂作用
添加(“SOAPAction”,“SOAPAction:urn#LstSbr\”);
NetworkCredential creds=新的网络凭据(“用户名”、“密码”);
所需凭证=凭证;
Req.Headers.Add(“MessageID”,“1”);//在头中添加MessageID
字符串DN=“+26342720450”;
string DOMAIN=“ims.telone.co.zw”;
//构建XML
string xmlRequest=string.Concat(
"",
"",
"  ",
"",
“”,DN,”,
“”,域“,
"    ",
"  ",
"");
//将请求拉入UTF-8字节数组
byte[]reqBytes=新的UTF8Encoding().GetBytes(xmlRequest);
//设置内容长度
Req.ContentLength=reqBytes.Length;
//将XML写入请求流
尝试
{
使用(Stream reqStream=Req.GetRequestStream())
{
reqStream.Write(reqBytes,0,reqBytes.Length);
}
}
捕获(例外情况除外)
{
Console.WriteLine(“类型异常”+ex.GetType().Name+“”+ex.Message);
Console.ReadLine();
投掷;
}
//标题和内容已设置,让我们调用服务
HttpWebResponse resp=(HttpWebResponse)Req.GetResponse();
字符串xmlResponse=null;
使用(StreamReader sr=new StreamReader(resp.GetResponseStream())
{
xmlResponse=sr.ReadToEnd();
}
Console.WriteLine(xmlResponse);
Console.ReadLine();
}
}
}

这是我用来发布到web服务的基本方法

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;
}
private void CreateTransaction(字符串webServiceUrl、字符串票据、双成本单位){
string soapAction=“Company.WebService/ICompanyWebService/CreatePurchaseTransaction”;
var soapEnvelope=新的XElement(soapNs+“信封”,
新的XAttribute(XNamespace.Xmlns+“soapenv”http://schemas.xmlsoap.org/soap/envelope/"),
新的XAttribute(XNamespace.Xmlns+“top”,“Company.WebService”),
新XElement(soapNs+主体),
新XElement(topNs+“CreatePurchaseTransaction”,
新的XElement(topNs+“命令”,
新XElement(topNs+“BillTransaction”、“true”),
新XElement(topNs+“BillingComments”,“由C代码创建”),
新XElement(topNs+“部门”、“开发”),
新的XElement(topNs+LineItems),GetManualPurchaseLineItems(topNs,costPerUnit)),
新条款(topNs+“附加费”、“42.21”),
新XElement(topNs+“税”、“真”),
新XElement(topNs+“TransactionDate”,DateTime.Now.ToString(“yyyy-MM-dd”))
))));
var webResp=ExecutePost(webServiceUrl、soapAction、soapEnvelope.ToString());
if(webResp.StatusCode!=HttpStatusCode.OK)
抛出新异常(“无法创建事务”);
var sr=新的StreamReader(webResp.GetResponseStream());
var xDoc=XDocument.Parse(sr.ReadToEnd());
var result=xDoc.subjects(topNs+“ResultType”).Single();
if(result.Value.Equals(“Success”,StringComparison.CurrentCultureIgnoreCase)==false)
抛出新异常(“无法发布购买交易。请查看xDoc以了解更多详细信息”);
}
私有IEnumerable GetManualPurchaseLineItems(XNamespace topNs,双成本单位){
var lineItems=新列表();
lineItems.Add(新的XElement(topNs+“PurchaseLineItem”,
新元素(topNs+“计数”,“5”),
新XElement(topNs+“费用类”、“技术时间”),
新XElement(topNs+“项目名称”、“刷牙和使用牙线”),
新XElement(topNs+“位置”、“您的房子”),
新的XElement(topNs+单位成本),costPerUnit.ToString(“#.00”);
返回行项目;
}

您需要将其应用到您的控制台应用程序中,但这有助于您继续吗?

看看itHey@nktsamba,您有机会解决这个问题吗?