首先,在我的测试中,我发现 DownloadStringCompleted 确实触发了。
但是,尝试读取事件 args Result 属性将引发错误。您需要测试事件 args Error 属性以确定是否发生错误。如果它具有此属性,则将包含对 WebException 的引用。
幸运的是WebException 有一个Response 对象,它的类型是WebResponse。您可以使用一个小函数从中获取响应字符串:-
string StringFromWebResponse(WebResponse response)
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
但是有一个问题。这仅在使用 ClientHTTP 堆栈而不是 BrowserHTTP 堆栈时可用。因此,您的应用程序中需要类似这行代码:-
WebRequest.RegisterPrefix("https://graph.facebook.com", System.Net.Browser.WebRequestCreator.ClientHttp);
那么这样的代码就可以工作了:-
WebClient client = new WebClient();
client.DownloadStringCompleted += (s, args) =>
{
string result;
if (args.Error == null)
{
result = args.Result;
//Do something with the expected result
}
else
{
WebException err = args.Error as WebException;
result = StringFromWebResponse(err.Response);
// Do something with the error result
}
};
client.DownloadStringAsync(new Uri("https://graph.facebook.com/me?access_token=your_token", UriKind.Absolute));
哦,但可能还有另一个问题。我对 facebook API 一无所知,但如果依赖于 cookie,那么默认情况下 ClientHTTP 堆栈本身并不管理 cookie。要正确处理 cookie,您需要为使用的每个 HttpWebRequest 分配一个公共 CookieContainer。 WebClient 不允许您访问使用的 WebRequest 对象,因此您需要直接使用 WebRequest/WebResponse。