如何从HttpResponseMessage.Content.ReadAsStringAsync()返回Task <t>。ContinueWith()方法?</t>

时间:2015-03-21 02:34:35

标签: c# c#-4.0 httpclient

我正在尝试使用HttpClient类获取/发布并面临以下问题

  1. 不知道如何从HttpResponseMessage.Content.ReadAsStringAsync()。ContinueWith()方法返回任务。
  2. 出于某种原因,它会继续自动取消

        private static Task<T> HttpClientSendAsync<T>(string url, object data, HttpMethod method, string contentType, CancellationToken token)
    {
        HttpRequestMessage httpRequestMessage = new HttpRequestMessage(method, url);
        RetryDelegatingHandler retryDelegatingHandler = new RetryDelegatingHandler();
        retryDelegatingHandler.PreAuthenticate = true;
        retryDelegatingHandler.Credentials = Credential;
        retryDelegatingHandler.Proxy = null;
    
        HttpClient httpClient = new HttpClient(retryDelegatingHandler);
        httpClient.Timeout = new TimeSpan(Constants.TimeOut);
    
        if (data != null)
        {
            byte[] byteArray = Encoding.ASCII.GetBytes(Helper.ToJSON(data));
            MemoryStream memoryStream = new MemoryStream(byteArray);
            httpRequestMessage.Content = new StringContent(new StreamReader(memoryStream).ReadToEnd(), Encoding.UTF8, contentType);
        }
    
        Task<HttpResponseMessage> httpResponseMessage = httpClient.SendAsync(httpRequestMessage);
        httpResponseMessage.ContinueWith((task) =>
            {
                if (!task.IsFaulted)
                {
                    HttpResponseMessage response = task.Result;
                    response.Content.ReadAsStringAsync().ContinueWith(
                    (stringTask) =>
                    {
                        if (!stringTask.IsFaulted)
                        {
                            return Helper.FromJSON<T>(stringTask.Result);
                        }
                        else
                        {
                            Logger.Log(string.Format("SendAsyncRequest Task IsFaulted: {0} \nException: {1}", typeof(T), task.Exception));
                            UpdateError(typeof(T).ToString());
    
                            return default(T);
                        }
                    });
                }
                else
                {
                    Logger.Log(string.Format("SendAsyncRequest Task IsFaulted: {0} \nException: {1}", typeof(T), task.Exception));
                    UpdateError(typeof(T).ToString());
    
                    return default(T);
                }
            });
    }
    
  3. 更新:它确实有效,但在尝试处理故障时它仍无法正常工作。

        return httpClient.SendAsync(httpRequestMessage).ContinueWith(task =>
        {
            var response = task.Result;
            return response.Content.ReadAsStringAsync().ContinueWith(stringTask =>
            {
                var json = stringTask.Result;
                return Helper.FromJSON<T>(json);
            });
        }).Unwrap();
    

1 个答案:

答案 0 :(得分:1)

Task.ContinueWith返回继续任务:TaskTask<T>。如果我理解这个问题,在这种情况下你可以这样做:

var continuation = httpResponseMessage.ContinueWith((task) =>
    {
        if (!task.IsFaulted)
        {
            HttpResponseMessage response = task.Result;
            return response.Content.ReadAsStringAsync().ContinueWith(
            (stringTask) =>
            {

            ...

continuation最终会成为Task<Task<T>>,您可以致电.Unwrap()将其转换为代理任务Task<T>