Async method does not return asp.net mvc 4

I am having a problem with the async method that I implemented. The method basically makes the HttpRequest resource and deserializes the string if the request is successful. I wrote a test for a method and it works. But the method never returns when I call it from the controller?

public async Task<IEnumerable<T>> Get() { try { var resourceSegmentUri = new Uri(_uri, UriKind.Relative); var response = await _client.GetAsync(resourceSegmentUri); if (response.IsSuccessStatusCode) { var submission = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<IEnumerable<T>>(submission); } if (response.Content != null) { var message = response.Content.ReadAsStringAsync(); throw new WebException(message.Result, (WebExceptionStatus)response.StatusCode); } } catch (WebException e) { Logger.Error("GET Request failed with status: {0}", e.Status); throw; } throw new Exception(); } 

Code that never returns:

 public ActionResult Index() { var api = new Api(); var test = api.Get().Result; //Never returns return View(); } 

Test that works:

 [Test] public void GetShouldReturnIfSuccessfulRequest() { var api = new Api(); var submission = api.Get(); Console.WriteLine(JsonConvert.SerializeObject(submission)); Assert.NotNull(submission); } 

Does anyone know a problem?

+6
source share
1 answer

You have a dead end because you are calling .Result in your controller action.

If you use async/await , you also need to use asynchronous actions.

So something like this should fix it:

 public async Task<ActionResult> Index() { var api = new Api(); var test = await api.Get(); // Should return } 

There is an extensive article on this here: Using asynchronous methods in ASP.NET MVC 4

+10
source