Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP HttpClient GetAsync is not responding, nor timing out

I'm creating an Instagram API client on ASP MVC using HttpClient, I'm trying to make a get request but it fails without throwing exception or responding and doesn't respond to my timeout. Here is my code:

 public class InstagramService
 {
    private HttpClient Client = new HttpClient {
       BaseAddress = new Uri("https://api.instagram.com/v1/"),
       Timeout = TimeSpan.FromMilliseconds(500)
    };
    public async Task<InstagramUser> GetInstagramUser(long? userId = null)
    {
       InstagramUser User = null;
       string Parameter = (userId == null) ? "self" : userId.ToString();
       try {
          var response = await Client.GetAsync("users/" + Parameter + "/" + GetAccessToken());
          if (response.IsSuccessStatusCode)
          {
              User = await response.Content.ReadAsAsync<InstagramUser>();
          }
      }catch(Exception e)
      {
          Console.WriteLine(e.Message);
          Console.WriteLine(e.InnerException.Message);
      }
      return User;
    }

    private string GetAccessToken()
    {
        return "?access_token=" + DB.config_det_sys.Single(i => i.codigo == "ACCESS_TOKEN_INSTAGRAM" && i.estado == true).Valor;
    }

 }

EDIT

Here I add how I call my service on the Home Controller, I will still test changing the controller to async Task

public class HomeController : Controller
{
    private InstagramService IGService = new InstagramService();
    public ActionResult About()
    {
       var apiCall = IGService.GetInstagramUser();
       var model = apiCall.Result;
       return View(model);
    }
}

I tested on Postman trying to make the API call and it indeed worked, so where I'm failing to catch errors?

like image 782
David Ortega Avatar asked Mar 11 '23 08:03

David Ortega


1 Answers

Your problem is here:

var model = apiCall.Result;

As I describe on my blog, you shouldn't block on asynchronous code. It can cause a deadlock.

Instead of Result, use await:

var model = await apiCall;
like image 140
Stephen Cleary Avatar answered Mar 20 '23 06:03

Stephen Cleary