如何创建HttpWebRequest调用SOAP协议的.svc服务并编写测试?
完善调用SOAP .svc服务的HttpWebRequest实现
我来帮你把这个SOAP服务调用的代码补全并优化,你的基础框架已经有了,但还有几个关键细节需要完善才能正常发起请求。下面是完整的实现方案:
完整的CreateWebRequest方法
var url = "http://localhost:4000/SI.WS.Core/SIF/CaseService.svc"; var action = "http://localhost:4000/SI.WS.Core/SIF/CaseService.svc/GetCases"; internal static HttpWebRequest CreateWebRequest(string url, string action) { // 创建HttpWebRequest实例 HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url); // 设置SOAPAction头,告诉服务要调用的具体方法 webRequest.Headers.Add("SOAPAction", action); // 设置请求内容类型:SOAP请求必须是XML格式,编码用UTF-8 webRequest.ContentType = "text/xml;charset=utf-8"; // SOAP请求默认使用POST方法 webRequest.Method = "POST"; // 允许请求流写入(后续需要写入SOAP envelope) webRequest.AllowWriteStreamBuffering = true; return webRequest; }
如何使用这个方法发送SOAP请求
光创建请求还不够,你需要把SOAP请求体(XML格式的Envelope)写入到请求流中。这里给你一个调用GetCases方法的示例:
public static string CallGetCasesService() { var request = CreateWebRequest(url, action); // 构造SOAP请求的XML内容(需要根据你的服务接口参数调整) string soapEnvelope = @"<?xml version=""1.0"" encoding=""utf-8""?> <soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/""> <soap:Body> <GetCases xmlns=""http://localhost:4000/SI.WS.Core/SIF/""> <!-- 这里填写GetCases方法需要的参数,比如: <CaseId>123</CaseId> <Status>Active</Status> --> </GetCases> </soap:Body> </soap:Envelope>"; // 将SOAP内容写入请求流 using (Stream stream = request.GetRequestStream()) { byte[] buffer = Encoding.UTF8.GetBytes(soapEnvelope); stream.Write(buffer, 0, buffer.Length); } // 获取服务响应 using (WebResponse response = request.GetResponse()) using (StreamReader reader = new StreamReader(response.GetResponseStream())) { return reader.ReadToEnd(); } }
关键注意事项
- SOAPAction的正确性:要确保
action参数和服务WSDL中定义的一致,有些服务可能只需要命名空间+方法名(比如http://localhost:4000/SI.WS.Core/SIF/GetCases),如果你的写法报错,可以尝试去掉URL中的.svc部分。 - SOAP Envelope的结构:必须严格匹配服务接口的参数定义,你可以通过访问
http://localhost:4000/SI.WS.Core/SIF/CaseService.svc?wsdl查看WSDL,找到GetCases方法的参数结构来调整XML内容。 - 异常处理:实际使用时建议加上
try-catch块,处理网络错误、服务返回的SOAP Fault等情况。
内容的提问来源于stack exchange,提问作者Avinash Avate
相关产品推荐
相关产品推荐

