Silverlight 5 第一次使用 Web 失败 API 2 [clientaccesspolicy.xml]

Silverlight 5 fails the first time to consume a Web API 2 [clientaccesspolicy.xml]

关于我的网络问题的信息很少或没有。

我尝试使用库托管在不同服务器 (localhost:/9000) 上的 Web API:Silverlight 5 项目 (localhost:/8080) 中的 HttpClient。

细节是 WebClient 完美工作,因为在你得到“clientaccesspolicy.xml”文件之前,调用服务确实(所以我解释):

WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.Headers["Accept"] = "application/json";
client.DownloadStringAsync(new Uri("http://localhost:9000/api/Orders"));
return ordersList;

HttpClient 在第一次尝试中并非如此失败:TimeOut 的“TaskCanceledException”,一旦(通过 Fiddler)完成操作,然后完美获得:cap.xml如果 Web API 格式为 JSON,则方法调用的第二次尝试 有效。

using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(@"http://localhost:9000/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                try
                {
                    client.Timeout = TimeSpan.FromMilliseconds(15000);
                    var response = await client.GetStringAsync("api/Orders").ConfigureAwait(false);
                    return JsonConvert.DeserializeObject<IEnumerable<ClassOrders>>(response);
                }
                catch (HttpRequestException h)
                {
                    Console.WriteLine(h.Message);
                }
                catch (TimeoutException t)
                {
                    Console.WriteLine(t.Message);
                }
                catch (TaskCanceledException c)
                {
                    Console.WriteLine(c.Message);
                }
            }

ConfigureAwait(false); //I may return if the asynchronous method fails (not frozen in subthread)

终于在this article的帮助下得到了答案

ConfigureAwait(false) 阻止了对结果的导航,当然,由于在线等待时间过长,任务被取消。

... ().Wait() 和 ConfigureAwait() 将有其他更有价值的用途,我的错误是认为没有它们就不可能捕获错误请求,而 HttpRequestException 在那里拯救了我。