![](/img/trans.png)
[英]HttpWebRequest/HttpWebResponse only works from Console app not ASP.NET
[英]WebClient call to REST service works in console app but not in asp.net
我正在調用一個測試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上進行某種類型的設置或選項設置,以使其像在Console App中一樣在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
指令中。 我嘗試了這種方法,它按預期工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.