我正在调用一个测试REST Web服务,它基本上将一个字符串作为输入,并将其回送给调用者。我在C#控制台应用程序中有以下代码:
static async Task RunAsync()
{
using (var client = new HttpClient())
{
string baseAddress =
"http://xxx.xxx.xxx.xxx/Services/OnyxCloudSyncService.svc/pingSync";
client.BaseAddress = new Uri(baseAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await
client.GetAsync("?sampleJson={SAMPLEJSON}");
if (response.IsSuccessStatusCode)
{
string txtBlock = await response.Content.ReadAsStringAsync();
Console.WriteLine(txtBlock);
Console.ReadKey();
}
}
}
此代码运行完美。但是,当我基本上将相同的代码复制到ASP.NET页面的代码隐藏中时,我对服务的调用超时:
using (var SyncClient = new HttpClient())
{
string baseAddress = "http://xxx.xxx.xxx.xxx/Services/OnyxCloudSyncService.svc/pingSync";
SyncClient.DefaultRequestHeaders.Accept.Clear();
SyncClient.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await
SyncClient.GetAsync("?sampleJson={SAMPLEJSON}");
if (response.IsSuccessStatusCode)
{
string txtBlock = await response.Content.ReadAsStringAsync();
Response.Write(txtBlock);
Response.End();
}
else
{
Response.Write("Error Calling service");
Response.End();
}
}
我从这个页面得到的错误是:
System.Net.Sockets.SocketException: A connection attempt failed because
the connected party did not properly respond after a period of time, or
established connection failed because connected host has failed to respond
xxx.xxx.xxx.xxx:80.
我是否需要在WebClient上设置某种类型的设置或选项,使其在ASP页面中工作,就像在Console App中一样?我不知道为什么这可以在控制台应用程序中工作,而不是在ASP.NET网页中。
答案 0 :(得分:1)
您可能遇到问题,因为没有等待结果,可以在以下位置找到解决方案:http://www.hanselman.com/blog/TheMagicOfUsingAsynchronousMethodsInASPNET45PlusAnImportantGotcha.aspx
我假设你使用的是.NET 4.5。
将方法编辑为实例,而不是静态,因为您将无法访问Response
对象:
async Task RunAsync()
{
using (var client = new HttpClient())
{
string baseAddress =
"http://74.120.219.166/Services/OnyxCloudSyncService.svc/pingSync";
client.BaseAddress = new Uri(baseAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await
client.GetAsync("?sampleJson={SAMPLEJSON}");
if (response.IsSuccessStatusCode)
{
string txtBlock = await response.Content.ReadAsStringAsync();
Response.Write(txtBlock);
Response.End();
}
else
{
Response.Write("Error Calling service");
Response.End();
}
}
}
运行方法,例如:RegisterAsyncTask(new PageAsyncTask(RunAsync));
将Async="true"
放在.aspx页面的Page
指令中。
我尝试了这种方法,它按预期工作。