A task was canceled with IHttpClientFactory

melon NG 291 Reputation points
2022-08-05T04:37:13.823+00:00

I made a post method with IHttpClientFactory with .net 6 like this:

public object Post(string URL,object PostObject,  Type ResponseObjectType)  
        {  
            try  
            {  
                var client = clientFactory.CreateClient();                  
                client.Timeout = TimeSpan.FromSeconds(3);  
                var options = new JsonSerializerOptions();  
                options.Encoder = System.Text.Encodings.Web.JavaScriptEncoder.Create(UnicodeRanges.All);  
                string JsonContent = JsonSerializer.Serialize(PostObject, PostObject.GetType(), options);                  
                var response = client.PostAsync(URL, new StringContent(JsonContent, Encoding.UTF8, "application/json")).Result;  
                if (response.StatusCode == System.Net.HttpStatusCode.NotFound || response.Content == null)  
                {  
                    client.Dispose();  
                    return null;  
                }  
                else  
                {  
                    object Result;  
                    if (ResponseObjectType == typeof(string))  
                    {  
                        Result = response.Content.ReadAsStringAsync().Result;  
                    }  
                    else  
                    {  
                        Result = response.Content.ReadFromJsonAsync(ResponseObjectType, options).Result;  
                    }  
                    client.Dispose();  
                    return Result;  
                }  
            }  
            catch (Exception ex)  
            {  
                LogException(ex, URL);  
                return null;  
            }  
        }  

Sometimes (not always) the code runs with the error above:

System.Threading.Tasks.TaskCanceledException: A task was canceled.
at System.Threading.Tasks.Task.GetExceptions(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task1.GetResultCore(Boolean waitCompletionNotification) at SIComponent.Global.Post(String URL, Object PostObject, Type ResponseObjectType) in C:\Project\Sample\SIComponent\Global.cs:line 317 at SIComponent.Middleware.BlackListMiddleware.Invoke(HttpContext context) in C:\Project\Sample\SIComponent\Middleware\BlackListMiddleware.cs:line 135 at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine) at SIComponent.Middleware.BlackListMiddleware.Invoke(HttpContext context) at SIComponent.Middleware.RedirectUpperURLMiddleware.InvokeAsync(HttpContext context) in C:\Project\Sample\SIComponent\Middleware\RedirectUpperURLMiddleware.cs:line 31 at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine) at SIComponent.Middleware.RedirectUpperURLMiddleware.InvokeAsync(HttpContext context) at SIComponent.Middleware.ExceptionMiddleware.Invoke(HttpContext context) in C:\Project\Sample\SIComponent\Middleware\ExceptionMiddleware.cs:line 25 at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine) at SIComponent.Middleware.ExceptionMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context) at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine) at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext) at Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.Invoke(HttpContext context) at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine) at Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware.Invoke(HttpContext context) at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine) at Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.TryServeStaticFile(HttpContext context, String contentType, PathString subPath) at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Builder.UseWhenExtensions.<>c__DisplayClass0_1.<UseWhen>b__1(HttpContext context) at Microsoft.AspNetCore.Rewrite.RewriteMiddleware.Invoke(HttpContext context) at Marvin.Cache.Headers.HttpCacheHeadersMiddleware.HandleResponse(HttpContext httpContext) at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine) at Marvin.Cache.Headers.HttpCacheHeadersMiddleware.HandleResponse(HttpContext httpContext) at Marvin.Cache.Headers.HttpCacheHeadersMiddleware.Invoke(HttpContext httpContext, IValidatorValueInvalidator validatorValueInvalidator) at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine) at Marvin.Cache.Headers.HttpCacheHeadersMiddleware.Invoke(HttpContext httpContext, IValidatorValueInvalidator validatorValueInvalidator) at lambda_method1(Closure , Object , HttpContext , IServiceProvider ) at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.<>c__DisplayClass5_1.<UseMiddleware>b__2(HttpContext context) at Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.Invoke(HttpContext context, ICorsPolicyProvider corsPolicyProvider) at lambda_method2(Closure , Object , HttpContext , IServiceProvider ) at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.<>c__DisplayClass5_1.<UseMiddleware>b__2(HttpContext context) at Microsoft.AspNetCore.HostFiltering.HostFilteringMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Hosting.HostingApplication.ProcessRequestAsync(Context context) at Microsoft.AspNetCore.Server.IIS.Core.IISHttpContextOfT1.ProcessRequestAsync()
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.StartTStateMachine
at Microsoft.AspNetCore.Server.IIS.Core.IISHttpContextOfT`1.ProcessRequestAsync()
at Microsoft.AspNetCore.Server.IIS.Core.IISHttpContext.HandleRequest()
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.StartTStateMachine
at Microsoft.AspNetCore.Server.IIS.Core.IISHttpContext.HandleRequest()
at Microsoft.AspNetCore.Server.IIS.Core.IISHttpContext.Execute()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading.PortableThreadPool.WorkerThread.WorkerThreadStart()
at System.Threading.Thread.StartCallback()
--- End of stack trace from previous location ---

In addition, every time it throws error when posting the same URL at the code:
var response = client.PostAsync(URL, new StringContent(JsonContent, Encoding.UTF8, "application/json")).Result;

What's wrong with this? Is it the problem with the remote server or my code? Thank you.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,162 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Laxmikant 216 Reputation points
    2022-08-05T20:10:28.737+00:00

    you need to use async and await, change the following code and try

    public async object Post(string URL,object PostObject,  Type ResponseObjectType)  
     {  
    					     
    		\\ other code  
    		    
    		 var response = await client.PostAsync(URL, new StringContent(JsonContent, Encoding.UTF8, "application/json")).Result;  
    		   
    //other code  
      
     }