Why do I get this TaskCanceledException error when consuming an api per post?

0

I tell you that I am making an application in asp.net mvc 5 before which I am consuming an api by means of asynchronous methods Task<> . For this I have a method created with which I consume data through request post but it gives me a task cancellation exception.

This error only happens to me when I consume a particular url since when I consume others by post I do not have this problem. To consume the other urls I pass an authorization token, but this url in particular does not need it. The error below.

  

A task has been canceled.   Description: Unhandled exception when executing the current Web request. Check the stack trace for more information about the error and where it originated in the code.

     

Exception details: System.Threading.Tasks.TaskCanceledException: A task was canceled.

     

Source code error:

     

Line 45: {   Line 46: RootObject RootObject = null;   Line 47: HttpResponseMessage response = await HttpService.GenerateClient (). PostAsJsonAsync (path, model);   Line 48: if (response.IsSuccessStatusCode)   Line 49: {

Method to consume the api:

static async Task<Object> PostRutConfirmadoAsync(MiModelo model, string path)
    {
        RootObject RootObject = null;
        HttpResponseMessage response = await HttpService.GenerateClient().PostAsJsonAsync(path, model);
        if (response.IsSuccessStatusCode)
        {
            RootObject = await response.Content.ReadAsAsync<RootObject>();
        }

        return RootObject;
    }

The error gives me in this line HttpResponseMessage response = await HttpService.GenerateClient().PostAsJsonAsync(path, model);

    
asked by vcasas 07.05.2018 в 17:13
source

1 answer

0

You can improve your code by applying a timeout and handling the possible exceptions in the following way

static async Task<Object> PostRutConfirmadoAsync(MiModelo model, string path)
{
    try 
    {
        RootObject RootObject = null;
        using (var client = HttpService.GenerateClient())
        {
            client.Timeout = TimeSpan.FromMinutes(30);
            var response = await client.PostAsJsonAsync(path, model);
            if (response.IsSuccessStatusCode)
            {
                RootObject = await response.Content.ReadAsAsync<RootObject>();
            }
        } 
    }
    catch (OperationCanceledException oce) 
    {
        // Tratar el error de timeout o tarea cancelada
    }
    catch (Exception exc) {
        // Otros errores (HTTP 500, parsing errors)
    }   

    return RootObject;
}
    
answered by 08.05.2018 в 18:30