.NET(C#)和RAW肥皂交易

时间:2011-05-14 15:50:29

标签: c# .net soap

最近我遇到了.NET(C#)和SOAP Transmissions的噩梦。 我必须使用一个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请求(请求中没有XML),因此收到SOAP Fault和ERROR 500。

有什么想法吗?

我必须以某种方式手动执行此操作。我甚至尝试使用TCPClient(在较低级别处理它),但我的所有尝试都受挫。

1 个答案:

答案 0 :(得分:0)

您应该使用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 !!