Silverlight WebClient NOT receiving 400 Bad Request
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 attempt开发者_StackOverflow社区ing to fetch: https://graph.facebook.com/me?access_token=your_token
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 args Error
property to determine if an error occured. If it has this property will hold a reference to a WebException
.
Fortunately the WebException
has a Response
object which is of type WebResponse
. You can get the response string from this using a little function:-
string StringFromWebResponse(WebResponse response)
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
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:-
WebRequest.RegisterPrefix("https://graph.facebook.com", System.Net.Browser.WebRequestCreator.ClientHttp);
So then code like this will work:-
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));
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 each HttpWebRequest
used. WebClient
doesn't allow you access to the WebRequest
object used so you'll need to drop to using WebRequest
/WebResponse
directly.
精彩评论