【问题标题】:Silverlight WebClient NOT receiving 400 Bad RequestSilverlight WebClient 未收到 400 错误请求
【发布时间】:2011-08-26 14:36:00
【问题描述】:

我有一个 WebClient 并且我正在订阅 OnDownloadStringCompleted 事件处理程序。当服务器以 400 Bad Request 的标头响应时,OnDownloadStringCompleted Never 被触发。即使标题显示 400,我仍然需要响应是什么。有没有办法绕过这个?

这是我尝试获取的 URL: https://graph.facebook.com/me?access_token=your_token

【问题讨论】:

    标签: silverlight facebook-graph-api webclient


    【解决方案1】:

    首先,在我的测试中,我发现 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 分配一个公共 CookieContainerWebClient 不允许您访问使用的 WebRequest 对象,因此您需要直接使用 WebRequest/WebResponse

    【讨论】:

    • RegisterPrefix 似乎已经做到了。由于某种原因,它不会在错误 400 上触发,但它会使用前缀。感谢您的帮助!
    • @Peanut:我在没有 ClientHTTP 的情况下进行了测试,事件仍然会触发,如果它根本没有触发,IMO 将是一个严重的错误。如果您能够证明它不会触发,那么如果您可以创建一个小的 Repro 并将其包含在问题中,那就太好了。
    猜你喜欢
    • 2017-08-26
    • 1970-01-01
    • 2016-09-11
    • 1970-01-01
    • 2015-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-26
    相关资源
    最近更新 更多