Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

async calls using HttpClient on MVC4

I'm playing a little bit with this new technology in .net 4.5, I would like to check the code for this call and how should I control the errors or the response of my async call. The call is working perfectly, I need full control of possible errors returned from my service.

this is my code:

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;

namespace TwitterClientMVC.Controllers
{
    public class Tweets
    {
        public Tweet[] results;
    }

    public class Tweet
    {
        [JsonProperty("from_user")]
        public string UserName { get; set; }

        [JsonProperty("text")]
        public string TweetText { get; set; }
    }
}

public async Task<ActionResult> Index()
{                                             
    Tweets model = null;

    HttpClient client = new HttpClient();

    HttpResponseMessage response = await client.GetAsync("http://mywebapiservice");

    response.EnsureSuccessStatusCode();

    model = JsonConvert.DeserializeObject<Tweets>(response.Content.ReadAsStringAsync().Result);

    return View(model.results);            
}

Is this the better way to do it? or I'm missing something? Thanks

I refactor it, is this method async as well?

public async Task<ActionResult> Index() 
    {
        Tweets model = null;
        using (HttpClient httpclient = new HttpClient())
        {
            model = JsonConvert.DeserializeObject<Tweets>(
                await httpclient.GetStringAsync("http://search.twitter.com/search.json?q=pluralsight")
            );
        }
        return View(model.results);
    }
like image 465
rgx71 Avatar asked Mar 07 '13 15:03

rgx71


People also ask

How do you call async method in controller?

Asynchronous operations may only be started within an asynchronous handler or module or during certain events in the Page lifecycle. If this exception occurred while executing a Page, ensure that the Page is marked <%@ Page Async="true" %> .

How do you call async task ActionResult?

1 Answer. Show activity on this post. It is best for you to use async/await down the whole call stack which is possible with MVC. Mark your Action as async and then use the await keyword to wait for the results from the CsvReader method.

How call async method in MVC?

Async, Await And Asynchronous Programming In MVC. Async keyword is used to call the function/method as asynchronously. Await keyword is used when we need to get result of any function/method without blocking that function/method. Let's first establish what the purpose of this code is, in the first place.

How use async await in ASP NET MVC?

To do Async in ASP.NET MVC, all you have to is return a Task and use the async keyword in your action methods.


1 Answers

Is this the better way to do it?

The response.EnsureSuccessStatusCode(); will throw an exception if the status code returned by your remote service is different than 2xx. So you might want to use the IsSuccessStatusCode property instead if you want to handle the error yourself:

public async Task<ActionResult> Index()
{                                             
    using (HttpClient client = new HttpClient())
    {
        var response = await client.GetAsync("http://mywebapiservice");

        string content = await response.Content.ReadAsStringAsync();
        if (response.IsSuccessStatusCode)
        {
            var model = JsonConvert.DeserializeObject<Tweets>(content);
            return View(model.results);            
        }

        // an error occurred => here you could log the content returned by the remote server
        return Content("An error occurred: " + content);
    }
}
like image 168
Darin Dimitrov Avatar answered Sep 26 '22 07:09

Darin Dimitrov