Silverlight WebClient 未收到 400 错误请求
我有一个 WebClient,并且正在订阅 OnDownloadStringCompleted 事件处理程序。当服务器响应 400 Bad Request 标头时,永远不会触发 OnDownloadStringCompleted。即使标题显示 400,我仍然需要响应是什么。有没有办法绕过这个?
这是我尝试获取的 URL: https://graph.facebook.com/me?access_token=your_token
I have a WebClient and I'm subscribing to the OnDownloadStringCompleted event handler. When the server responds with a header of 400 Bad Request, the OnDownloadStringCompleted Never gets triggered. I still need what the response is even though the header says 400. Is there a way to bypass this?
Heres the URL I'm attempting to fetch:
https://graph.facebook.com/me?access_token=your_token
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,在我的测试中,我发现 DownloadStringCompleted 确实会触发。
但是,尝试读取事件参数
Result
属性将引发错误。您需要测试事件参数Error
属性以确定是否发生错误。如果它具有此属性,则将保存对WebException
的引用。幸运的是,
WebException
有一个Response
对象,其类型为WebResponse
。您可以使用一个小函数从中获取响应字符串:-但有一个问题。仅当使用 ClientHTTP 堆栈而不是 BrowserHTTP 堆栈时才可用。所以你的应用程序中需要这样的代码:-
那么这样的代码就可以工作:-
哦,但可能还有另一个问题。我对 facebook API 一无所知,但如果存在对 cookie 的依赖,那么默认情况下 ClientHTTP 堆栈本身不管理 cookie。要正确处理 cookie,您需要为每个使用的
HttpWebRequest
分配一个通用的CookieContainer
。WebClient
不允许您访问所使用的WebRequest
对象,因此您需要转而使用WebRequest
/WebResponse 直接。
First off all in my testing I find that the DownloadStringCompleted does fire.
However an attempt to read the event args
Result
property will throw an error. You need to test the event argsError
property to determine if an error occured. If it has this property will hold a reference to aWebException
.Fortunately the
WebException
has aResponse
object which is of typeWebResponse
. You can get the response string from this using a little function:-But there is a problem. This is only available when using the ClientHTTP stack not the BrowserHTTP stack. So you need something like this line of code in your app:-
So then code like this will work:-
Oh but there is possibly another problem. I don't know anything about the facebook API but if there is a dependency on cookies then by default the ClientHTTP stack doesn't manage cookies itself. To handle cookies properly you need to assign a common
CookieContainer
to eachHttpWebRequest
used.WebClient
doesn't allow you access to theWebRequest
object used so you'll need to drop to usingWebRequest
/WebResponse
directly.