gpt4 book ai didi

c# - 对 REST 服务的 WebClient 调用在控制台应用程序中有效,但在 asp.net 中无效

转载 作者:行者123 更新时间:2023-11-30 12:43:55 27 4
gpt4 key购买 nike

我正在调用一个测试 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 页面中像在控制台应用程序中一样工作?我不知道为什么这会在控制台应用程序而不是 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();
}
}
}

运行方法如下:RegisterAsyncTask(new PageAsyncTask(RunAsync));Async="true" 放入 .aspx 页面的 Page 指令中。我尝试了这种方法,它按预期工作。

关于c# - 对 REST 服务的 WebClient 调用在控制台应用程序中有效,但在 asp.net 中无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29848819/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com