我正在调用一个测试 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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
这段代码运行完美。但是,当我将相同的代码复制到 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();
}
}
Run Code Online (Sandbox Code Playgroud)
我从该页面得到的错误是:
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.
Run Code Online (Sandbox Code Playgroud)
我是否需要在 WebClient 上设置某种类型的设置或选项,以使其在 ASP 页面中像在控制台应用程序中一样工作?我不明白为什么这可以在控制台应用程序中工作,而不能在 ASP.NET 网页中工作。
您可能遇到问题,因为没有等待结果,解决方案可能会在以下位置找到: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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
运行方法如下:RegisterAsyncTask(new PageAsyncTask(RunAsync));
放入.aspx 页面的指令。我尝试了这种方法并且它按预期工作。Async="true"
Page