我正在使用.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);
}
答案 0 :(得分: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);
}
}