refit: [BUG] Using refit to call external API sometimes hang

I’m using .NET core 3 and Refit 5.0.23 to call an external API. Sometimes it works fine, but sometimes it hangs and throw error below:

I checked the external API using Postman it returns data very quick and no issues with calling it. But calling through Refit sometimes hang. Has anyone encountered this before?

THanks.

TaskCanceledException { Task: null, CancellationToken: CancellationToken { IsCancellationRequested: True, CanBeCanceled: True, WaitHandle: “The property accessor threw an exception: ObjectDisposedException” }, TargetSite: Void MoveNext(), StackTrace: " at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.HttpConnectionPool.SendWithNtConnectionAuthAsync(HttpConnection connection, HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken) at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken) at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.DiagnosticsHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.HttpClient.FinishSendAsyncUnbuffered(Task1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts) at Refit.RequestBuilderImplementation.<>c__DisplayClass14_02.<<BuildCancellableTaskFuncForMethod>b__0>d.MoveNext() in d:\a\1\s\Refit\RequestBuilderImplementation.cs:line 249 — End of stack trace from previous location where exception was thrown — at WebAPI.QueryHandler.Handle(Query query, CancellationToken cancellationToken) in D:\WebAPI\Features\QueryHandler.cs:line 79 at MediatR.Pipeline.RequestExceptionProcessorBehavior2.Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate1 next) at MediatR.Pipeline.RequestExceptionProcessorBehavior2.Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate1 next) at MediatR.Pipeline.RequestExceptionActionProcessorBehavior2.Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate1 next) at MediatR.Pipeline.RequestExceptionActionProcessorBehavior2.Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate1 next) at MediatR.Pipeline.RequestPreProcessorBehavior2.Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate1 next) at MediatR.Pipeline.RequestPostProcessorBehavior2.Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate1 next) at MediatR.Pipeline.RequestPreProcessorBehavior2.Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate1 next) at WebAPI.Behaviors.LoggingBehavior2.Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate1 next) in D:\WebAPI\Behaviors\LoggingBehavior.cs:line 15 at WebAPI.Behaviors.ValidationBehavior2.Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate1 next) in D:\WebAPI\Behaviors\ValidatorBehavior.cs:line 54 at WebAPI.Controllers.Query.GetQuery(Query query) in D:\WebAPI\Features\Query\Query.cs:line 32 at lambda_method(Closure , Object ) at Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable.Awaiter.GetResult() at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask1 actionResultValueTask) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.<Invoke>g__AwaitMatcher|8_0(EndpointRoutingMiddleware middleware, HttpContext httpContext, Task1 matcherTask) at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext) at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider) at WebAPI.Middleware.CustomExceptionMiddleware.Invoke(HttpContext context) in D:\WebAPI\Middlewares\CustomExceptionMiddleware.cs:line 36", Message: “The operation was canceled.”, Data: [], InnerException: IOException { TargetSite: Void ThrowException(System.Net.Sockets.SocketError, System.Threading.CancellationToken), StackTrace: " at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken) at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.GetResult(Int16 token) at System.Net.Security.SslStream.<FillBufferAsync>g__InternalFillBufferAsync|215_0[TReadAdapter](TReadAdapter adap, ValueTask1 task, Int32 min, Int32 initial) at System.Net.Security.SslStream.ReadAsyncInternal[TReadAdapter](TReadAdapter adapter, Memory1 buffer) at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)", Message: “Unable to read data from the transport connection: The I/O operation has been aborted because of either a thread exit or an application request…”, Data: [], InnerException: SocketException { Message: “The I/O operation has been aborted because of either a thread exit or an application request.”, SocketErrorCode: OperationAborted, ErrorCode: 995, NativeErrorCode: 995, TargetSite: null, StackTrace: null, Data: [], InnerException: null, HelpLink: null, Source: null, HResult: -2147467259 }, HelpLink: null, Source: “System.Net.Sockets”, HResult: -2146232800 }, HelpLink: null, Source: “System.Net.Http”, HResult: -2146233029 }

Environment

  • OS: Windows 10 Pro
  • Device: CPU with i7

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 3
  • Comments: 18 (1 by maintainers)

Most upvoted comments

FYI for anyone else who got this issue and wound up here. I had this issue - even with Refit 6.0. I would get two successful POSTs, and then the third would hang up until there was a 100 second timeout that bubbled up as a TaskCanceledException.

Here’s what it was at the end of the day: The definition of the Refit interface call. Because the POST was not returning anything meaningful, but I DID want to get the status code, I had found other guidance to define the method as: Task<HttpResponseMessage> AddActualValue(string projectId, ActualObject o);

The answer was to change to: Task<ApiResponse<string>> AddActualValue(string projectId, ActualObject o);

Suddenly everything was fine again. Not sure why the issue happened the way it did, but spent a day or so fighting it, so I figured I’d pass it on…

i just revise @mattmas answer, to work properly you mas add a body serialize URL encoded in refit 6.0 Task<ApiResponse<WrapperAbsenceResponse>> PostAbsencesAsync([Body(BodySerializationMethod.UrlEncoded)] PostAbsencesRequest postAbsences);

this for POST type API

I’ve got the same issue ruining it from a Lambda. It fails less than 1% of the time, but it would be good to understand why it does fail.

System.Threading.Tasks.TaskCanceledException: The operation was canceled. ---> System.IO.IOException: Unable to read data from the transport connection: Operation canceled. ---> System.Net.Sockets.SocketException: Operation canceled
   --- End of inner exception stack trace ---
   at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error)
   at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.GetResult(Int16 token)
   at System.Net.Security.SslStreamInternal.<FillBufferAsync>g__InternalFillBufferAsync|38_0[TReadAdapter](TReadAdapter adap, ValueTask`1 task, Int32 min, Int32 initial)
   at System.Net.Security.SslStreamInternal.ReadAsyncInternal[TReadAdapter](TReadAdapter adapter, Memory`1 buffer)
   at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.SendWithNtConnectionAuthAsync(HttpConnection connection, HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
   at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)