我需要获取从Json反序列化的对象列表。
我的问题是这个代码在行responseMessage = await httpClient.GetAsync(uri);
中挂起我在Fiddler中检查了get和响应,我在Fiddler中获取Json,一切都有200代码,但由于某种原因代码不能继续下一步虽然在VS中进行调配,但它只会永远挂起。我在这段代码中缺少什么来获取对象列表?
由于代码在提到的行中挂起,因此问题必须在HttpClient中。
using (HttpClient httpClient = new HttpClient())
{
try
{
var headers = httpClient.DefaultRequestHeaders;
HttpResponseMessage responseMessage;
responseMessage = await httpClient.GetAsync(uri);
responseMessage.Content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/x-www-form-urlencoded; charset=UTF-8");
var content = responseMessage.Content.ReadAsStringAsync();
tvChannelList = JsonConvert.DeserializeObject<List<TvChannels>>(content.GetResults());
return tvChannelList;
}
catch (Exception ex)
{
throw;
}
}
提前感谢任何提示。
答案 0 :(得分:1)
问题是如此悲惨,我忘了将await
放在从Web服务调用数据的方法名称之前,从而阻止UI。
前
ListOfTvChannels = _remoteController.GetChannelListAsync();
后
ListOfTvChannels = await _remoteController.GetChannelListAsync();
感谢所有人的帮助。
答案 1 :(得分:0)
I use this method when using the HttpClient and want to return an object from a JSON response.
public async Task<TResult> MakeGetRequest<TResult>(string uri)
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Charset", "ISO-8859-1");
HttpResponseMessage response = await client.GetAsync(uri);
response.EnsureSuccessStatusCode();
var data = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<TResult>(data);
}
}