傳統 WCF 測試依賴客戶端代理,但基於 網絡 Socket 直接發送 SOAP 消息 的測試方式,能驗證線路層協議一致性、支援異構客戶端測試、並適合安全性/性能基線測試。本文完整演示從服務搭建到 Socket 測試工具的構建過程。
https://localhost:8000/MyWCFMathService/Service。IMathService,單一操作 Sum(double, double)。WSHttpBinding(SecurityMode.None) 便於抓包分析明文 SOAP。ServiceMetadataBehavior.HttpGetEnabled 供「添加服務引用」。ASP.NET Web Forms 客戶端通過生成的 MathServiceClient 調用服務,驗證功能正常。
使用 Fiddler 抓取常規客戶端請求,提取 SOAP 信封模板:
<s:Envelope xmlns:s="..." xmlns:a="...">
<s:Header>
<a:Action>https://tempuri.org/IMathService/Sum</a:Action>
<a:MessageID>urn:uuid:...</a:MessageID>
<a:ReplyTo>...</a:ReplyTo>
<a:To>https://localhost:8000/.../MathService</a:To>
</s:Header>
<s:Body>
<Sum xmlns="https://tempuri.org/">
<x>{input1}</x><y>{input2}</y>
</Sum>
</s:Body>
</s:Envelope>
string header =
"POST /MyWCFMathService/Service/MathService HTTP/1.1\r\n" +
"Content-Type: application/soap+xml; charset=utf-8\r\n" +
"SOAPAction: 'https://tempuri.org/IMathService/Sum'\r\n" +
"Host: localhost:8000\r\n" +
"Content-Length: " + soapMessage.Length + "\r\n" +
"Expect: 100-continue\r\n" +
"Connection: Close\r\n\r\n";
關鍵點:每行以 \r\n 結尾,雙 \r\n\r\n 分隔頭與體。
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(new IPEndPoint(IPAddress.Loopback, 8000));
byte[] sendBytes = Encoding.UTF8.GetBytes(header + soapMessage);
socket.Send(sendBytes);
// 分塊接收響應
byte[] buffer = new byte[512];
string response = "";
int bytesRead;
while ((bytesRead = socket.Receive(buffer)) > 0)
response += Encoding.UTF8.GetString(buffer, 0, bytesRead);
if (response.Contains(expected))
Console.WriteLine("Test result : Pass");
else
Console.WriteLine("Test result : **FAIL**");
Socket 測試雖需手工構建報文,但提供了最高靈活度與最真實的網絡層驗證能力,是 WCF 服務測試工具箱中的利器。