One Developer
One Developer

Reputation: 566

How to return the Task<T> from HttpResponseMessage.Content.ReadAsStringAsync().ContinueWith() method?

I am trying to Get/Post using the HttpClient Class and facing the following issues

  1. Do not know how to return the Task from HttpResponseMessage.Content.ReadAsStringAsync().ContinueWith() method.
  2. For some reason, it is keep on cancelling automatically

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

Update: It does work however still it does not work while trying to handle the Fault.

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

Upvotes: 2

Views: 2285

Answers (1)

othp
othp

Reputation: 331

Task.ContinueWith returns the continuation task: a Task or Task<T>. If I'm understanding the question, in your case here you could do something like this:

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

            ...

and continuation will end up being a Task<Task<T>> which you can call .Unwrap() on to turn that into a proxy task Task<T>.

Upvotes: 1

Related Questions