David Ortega
David Ortega

Reputation: 915

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?

Upvotes: 4

Views: 2766

Answers (2)

Nkosi
Nkosi

Reputation: 247088

Adding to Stephen's answer, update the controller's action to be async all the way.

public class HomeController : Controller {
    private InstagramService IGService = new InstagramService();
    public async Task<ActionResult> About() {
       var model = await IGService.GetInstagramUser();
       return View(model);
    }
}

Upvotes: 2

Stephen Cleary
Stephen Cleary

Reputation: 456457

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;

Upvotes: 5

Related Questions