【发布时间】:2015-05-07 16:16:59
【问题描述】:
关于网络我的问题的信息很少或没有。
我尝试通过库使用托管在不同服务器 (localhost:/9000) 上的 Web API:Silverlight 5 项目中的 HttpClient (localhost:/8080)。
细节是 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 在第一次尝试时并非如此失败:“TaskCanceledException” by TimeOut,一旦(通过 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)
【问题讨论】:
-
在 HTTPClient 示例中,URI 指向 8080 而不是 9000
-
@Kar,API 托管在“9000”(端口示例)和“8080”中的 WebApp -cliente-。示例:webapi.com 和客户 SL5 MyApp.com 两者都是单独的托管。如果您在代码中是正确的,并且它已被更正。谢谢。
标签: c# silverlight asp.net-web-api httpclient webclient