简体   繁体   中英

WebClient call to REST service works in console app but not in asp.net

I am calling a test REST web service that basically takes a string as input, and echoes it back to the caller. I have the following code, in a C# console app:

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();
    }
    }
}

This code runs perfectly. But when I essentially copy the same code into the code-behind for an ASP.NET page, I timeout on the call to the service:

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();
   }
  }

The error I get from this page is:

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. 

Would there be some type of setup or option I need to set on the WebClient to make it work in the ASP page like it does in the Console App? I am at a loss as to why this would work in a console app and not in an ASP.NET web page.

You might be having a problem because the result is not being waited for, the solution might be found on: http://www.hanselman.com/blog/TheMagicOfUsingAsynchronousMethodsInASPNET45PlusAnImportantGotcha.aspx

I assume you're using .NET 4.5. Edit method to be instance, not static since you won't be able to reach Response object:

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 method like: RegisterAsyncTask(new PageAsyncTask(RunAsync)); Put Async="true" in Page directive of your .aspx page. I tried this approach and it worked as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM