ASP HttpClient GetAsync is not responding, but timeout

I am creating an Instagram client interface on ASP MVC using HttpClient, I am trying to make a receive request, but it fails without throwing an exception or not responding and does not 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 the controller change for 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 Postman trying to make an API call and it really worked, so when can I not catch the errors?

+4
source share
2 answers

Your problem is here:

var model = apiCall.Result;

. .

Result await:

var model = await apiCall;
+4

, async .

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

Source: https://habr.com/ru/post/1664492/


All Articles