簡體   English   中英

.NET(C#)和RAW Soap事務

[英].NET (C#) and RAW Soap Transactions

最近,我在使用.NET(C#)和SOAP傳輸時遇到了噩夢。 我必須使用一個Web服務(這本來是一件容易的事),但是它變得很糟糕,似乎沒有任何效果。

HttpWebRequest webRequest = (HttpWebRequest)System.Net.WebRequest.Create("http://api.myapi.com/apis/services/theapi");

webRequest.AllowAutoRedirect = true;
webRequest.Timeout = 1000 * 30;
webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";
webRequest.PreAuthenticate = true;
webRequest.Method = "POST";
webRequest.Headers.Add("SOAPAction: \"\"");
webRequest.Accept = "text/xml";

WebResponse webResponse = null;

try
{
    webResponse = webRequest.GetResponse();

    Stream Stream = webRequest.GetRequestStream();
    string SoapEnvelope = "<soap:Envelope>...SOAP CODE ...</soap:Envelope>";
    StreamReader streamReader = new StreamReader(webResponse.GetResponseStream(), System.Text.Encoding.UTF8);

    XmlDocument SoapEnvelopeXML = new XmlDocument();
    SoapEnvelopeXML.LoadXml(SoapEnvelope);

    SoapEnvelopeXML.Save(Stream);

    string result = streamReader.ReadToEnd();
    return result;
}

當我嘗試使用Wireshark嗅探軟件包時,我得到的是:

---- CLIENT INPUT ------
POST /apis/services/theapi HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)
SOAPAction: ""
Accept: text/xml
Host: api.myapi.com

Connection: Keep-Alive

---- SERVER ANSWER ------

HTTP/1.1 500 Internal Server Error
Date: Sat, 14 May 2011 15:35:32 GMT
X-Powered-By: Servlet 2.4; JBoss-4.0.5.GA (build: CVSTag=Branch_4_0 date=200610162339)/Tomcat-5.5
Content-Type: text/xml;charset=ISO-8859-1
Content-Length: 225
Connection: close
X-Pad: avoid browser bug

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><soap:Fault><faultcode>soap:Client</faultcode><faultstring>Error reading XMLStreamReader.</faultstring></soap:Fault></soap:Body></soap:Envelope>

不出所料,由於我還沒有發布Soap Request(請求中沒有XML),因此收到SOAP Fault和ERROR 500。

有任何想法嗎?

我必須以某種方式手動執行此操作。 我甚至嘗試使用TCPClient(在較低級別上對其進行處理),但是我的所有嘗試都感到沮喪。

您應使用“ VS添加服務參考”向導將服務加載到項目中。 Add Service Reference從服務API端點的URL生成更高級別的類,以自動使用api。 它看起來像這樣:

MyApiClient client = new MyApiClient();
MyApiResult result;

try {
    client.Open();
    result = client.CallMethod(param1, param2, ...);
    client.Close();
} catch (Exception ex) {
    // do something with FaultException or API error
}

// do something with the result returned, if needed

如果正確完成,則不必處理HttpWebRequest ,顯式URL或手動鍵入任何SOAP XML!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM