反序列化httpclient的内容结果会产生间歇性的空值

时间:2016-07-04 12:10:36

标签: json asynchronous httpclient

我在pcl中有一个异步方法:

public async Task<T> Get<T>(string method) where T : EntityBase
    {
        try
        {
            Log.Info($"RequestURL {_client.BaseAddress}{method}");

            var response = await _client.GetAsync(method);
            var content = await response.Content.ReadAsStringAsync();

            if (response.StatusCode != HttpStatusCode.OK)
            {
                return HandleResponse<T>(response); //this method just handles failures and logs the info in aspecial way
            }

            Log.Info($"Response {content}");

            return JsonConvert.DeserializeObject<T>(content);
        }
        catch (Exception ex)
        {
            Log.Error($"Making api request to {method}. --- {ex.ToString()}");
            return default(T);
        } 
    }

我的handleresponse方法:

 private T HandleResponse<T>(HttpResponseMessage responseMessage) where T : EntityBase
    {           
        var resultType = RequestResultType.Success;
        var message = "OK";

        switch (responseMessage.StatusCode)
        {
            case HttpStatusCode.Unauthorized:
                resultType = RequestResultType.Failure;
                message = "Unauthorised";
                break;
        }

        Log.Info($"StatusCode: {responseMessage.StatusCode}");
        Log.Info($"ResultType: {resultType}");
        Log.Info($"Message: {message}");

        return (T)Activator.CreateInstance(typeof(T), resultType, message);
    }

上面T中表示的对象:

public class TaskItemList: EntitBase
{
    public List<TaskItem> Tasks { get; set; }
}

我遇到的问题是,同样的方法在调用时会随机将T返回为null。有时T部分填充,其中一些属性为null

当我通过浏览器调用API时,总会有一个值。

我怀疑响应内容还没有完全由json尝试反序列化时形成,但是如何处理呢?

0 个答案:

没有答案