我当前工作的一部分涉及使用外部web服务,我已经为其生成了客户端代理代码(使用WSDL.exe工具)。
我需要测试web服务是否能够正确处理缺少必填字段的情况。例如,姓氏和名字是必需的-如果调用中没有姓氏和名字,那么应该返回SOAP错误块。
正如您可能已经猜到的,在使用自动生成的代理代码时,我无法从web服务调用中排除任何必填字段,因为编译时会对模式进行检查。
我所做的是使用HttpWebRequest和HttpWebResponse向web服务发送/接收手动格式化的SOAP信封。这是可行的,但由于服务返回500 HTTP状态码,因此在客户端上引发异常,并且响应(包含我需要的SOAP故障块)为空。基本上,我需要返回流来获取错误数据,以便完成单元测试。我知道返回了正确的数据,因为我可以在Fiddler跟踪中看到它,但我无法在代码中找到它。
下面是我为手动呼叫所做的,更改名称以保护无辜者:
private INVALID_POST = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope ...rest of SOAP envelope contents...";
private void DoInvalidRequestTest()
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://myserviceurl.svc");
request.Method = "POST";
request.Headers.Add("SOAPAction",
"\"https://myserviceurl.svc/CreateTestThing\"");
request.ContentType = "text/xml; charset=utf-8";
request.ContentLength = INVALID_POST.Length;
request.KeepAlive = true;
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(invalidPost);
}
try
{
// The following line will raise an exception because of the 500 code returned
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string reply = reader.ReadToEnd();
}
}
}
catch (Exception ex)
{
... My exception handling code ...
}
}
请注意,我没有使用WCF,只使用WSE 3。