如何等待对web服务的调用完成
本文关键字:服务 调用 web 何等待 等待 | 更新日期: 2023-09-27 18:30:04
我正在尝试从web服务获取FedAuth Cookie。但实际情况是,在我从web服务获得结果之前,另一个方法GetFedAuthCookieFromSOAPResponse
方法正在执行,传递给它的参数变成了null
。因此,我得到了一个例外:
startIndex不能大于字符串的长度。参数名称:startIndex
如何等待从web服务获得soap响应,然后执行方法GetFedAuthCookieFromSOAPResponse
?
static void Main(string[] args)
{
string url = "https://server/site";
string soapResponse = GetSOAPResponse(url, "http://site/server/exapmle.asmx");
Console.WriteLine(GetFedAuthCookieFromSOAPResponse(soapResponse));
Console.WriteLine("Press ENTER to close program");
Console.ReadLine();
}
internal static string GetSOAPResponse(string url, string serviceURL)
{
using (WebClient client = new WebClient())
{
string request = "<?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><GetFedAuthCookie xmlns='"http://tempuri.org/'"><requestUrl>" + url + "</requestUrl><userName></userName><password></password></GetFedAuthCookie></soap:Body></soap:Envelope>";
client.Headers.Add(HttpRequestHeader.ContentType, "text/xml; charset=utf-8");
client.Headers.Add("SOAPAction", "http://tempuri.org/GetFedAuthCookie");
string soapResult = string.Empty;
client.UploadString(new Uri(serviceURL), request);
client.UploadStringCompleted += new UploadStringCompletedEventHandler(delegate(object sender, UploadStringCompletedEventArgs e)
{
soapResult = e.Result;
});
return soapResult;
}
}
internal static string GetFedAuthCookieFromSOAPResponse(string soapResponse)
{
string openingTag = "<GetFedAuthCookieResult>";
string closingTag = "</GetFedAuthCookieResult>";
int startIndex = soapResponse.IndexOf(openingTag) + openingTag.Length;
int length = soapResponse.IndexOf(closingTag) - startIndex;
return soapResponse.Substring(startIndex, length);
}
UploadString
已经是一个同步方法。这意味着当方法返回时,操作已经完成。CCD_ 5仅在处理像UploadStringAsync
或UploadStringTaskAsync
这样的异步方法时使用。
UploadString
返回一个字符串,该字符串是来自服务器的响应。
你只需要
string soapResult = client.UploadString(new Uri(serviceURL), request);
return soapResult;
这是您响应web服务请求完成的地方:
client.UploadStringCompleted += new UploadStringCompletedEventHandler(delegate(object sender, UploadStringCompletedEventArgs e)
{
soapResult = e.Result;
});
所以你可以在那里执行你的后续逻辑:
client.UploadStringCompleted += new UploadStringCompletedEventHandler(delegate(object sender, UploadStringCompletedEventArgs e)
{
Console.WriteLine(GetFedAuthCookieFromSOAPResponse(e.Result));
Console.WriteLine("Press ENTER to close program");
Console.ReadLine();
});
或者,您可以将该逻辑重构为一个方法,并从中调用该方法,等等。
但本质上,由于这是一个异步操作,您不会"等到它完成",而是"响应它的完成事件"。