async calls using HttpClient on MVC4

后端 未结 1 816
無奈伤痛
無奈伤痛 2021-01-02 23:19

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

相关标签:
1条回答
  • 2021-01-02 23:34

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题