【发布时间】:2011-07-20 18:43:50
【问题描述】:
private static string WebServiceCall(string methodName)
{
WebRequest webRequest = WebRequest.Create("http://localhost/AccountSvc/DataInquiry.asmx");
HttpWebRequest httpRequest = (HttpWebRequest)webRequest;
httpRequest.Method = "POST";
httpRequest.ContentType = "text/xml; charset=utf-8";
httpRequest.Headers.Add("SOAPAction: http://tempuri.org/" + methodName);
httpRequest.ProtocolVersion = HttpVersion.Version11;
httpRequest.Credentials = CredentialCache.DefaultCredentials;
Stream requestStream = httpRequest.GetRequestStream();
//Create Stream and Complete Request
StreamWriter streamWriter = new StreamWriter(requestStream, Encoding.ASCII);
StringBuilder soapRequest = new StringBuilder("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
soapRequest.Append(" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" ");
soapRequest.Append("xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body>");
soapRequest.Append("<GetMyName xmlns=\"http://tempuri.org/\"><name>Sam</name></GetMyName>");
soapRequest.Append("</soap:Body></soap:Envelope>");
streamWriter.Write(soapRequest.ToString());
streamWriter.Close();
//Get the Response
HttpWebResponse wr = (HttpWebResponse)httpRequest.GetResponse();
StreamReader srd = new StreamReader(wr.GetResponseStream());
string resulXmlFromWebService = srd.ReadToEnd();
return resulXmlFromWebService;
}
我尝试了不同的代码来发送/接收肥皂响应,但都以相同的"The remote server returned an error: (500) Internal Server Error." 失败。
我可以使用 SoapUI 访问相同的服务。我也能够调用该方法。我在这个论坛上读到我收到 500 错误的原因可能是错误的标题。我验证了标题,它似乎没问题。如果有人可以提供帮助,我将不胜感激。
以下是示例 SOAP 请求:
POST /AccountSvc/DataInquiry.asmx HTTP/1.1
Host: abc.def.gh.com
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://tempuri.org/GetMyName"
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetMyName xmlns="http://tempuri.org/">
<name>string</name>
</GetMyName>
</soap:Body>
</soap:Envelope>
我使用上面的示例请求来执行该方法并且它有效。这是我通过的 Soap 请求:
<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><GetMyName xmlns="http://tempuri.org/"><name>Sam</name></GetMyName></soap:Body></soap:Envelope>
编辑:
我已经更新了 WebServiceCall 中适用于 .asmx 服务的上述代码。但是相同的代码不适用于 WCF 服务。为什么?
【问题讨论】:
-
更多提示:永远不要使用字符串操作来创建 XML。始终使用 XML API 之一,例如 LINQ to XML 或 XmlWriter。此外,Streams、StreamReader/Writers 和 WebResponse 需要在
using块中,这样它们就不会在发生异常时泄漏资源。 -
没有看到你的代码,可能很难说。我会冒险猜测您可能没有指定足够的行为。此链接可能对您有用,因为它描述了 WCF 端点/服务的 SOAP 配置:stackoverflow.com/questions/186631/…
标签: c# web-services soap asmx