6

我在 .net 4.5 中对这项新技术进行了一些尝试,我想检查此调用的代码以及我应该如何控制异步调用的错误或响应。该调用运行良好,我需要完全控制从我的服务返回的可能错误。

这是我的代码:

    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);            
}

这是更好的方法吗?或者我错过了什么?谢谢

我重构它,这个方法也是异步的吗?

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);
    }
4

1 回答 1

7

这是更好的方法吗?

如果远程服务返回的状态码不是 2xx ,response.EnsureSuccessStatusCode();则会抛出异常。IsSuccessStatusCode因此,如果您想自己处理错误,您可能想使用该属性:

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);
    }
}
于 2013-03-07T15:16:12.660 回答