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;
}
我尝试了不同的代码来发送/接收SOAP响应,但都失败并显示相同的错误信息"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>
编辑:
我已经更新了上面的代码,可以在使用 .asmx 服务时正常工作。但是同样的代码在使用 WCF 服务时却不起作用。为什么?
using
块中,以便在发生异常时不会泄漏资源。 - John Saunders