"invalid handle was passed to the function" on MoveNext when another process is sending many messages - c#

I am trying to create an application that oversees message queues as they are processing messages.
To snapshot the message queue, i wrote the following code:
MessageEnumerator msgEnum = null;
try
{
// some code that fetches q (the queue)
msgEnum = q.GetMessageEnumerator2();
while (msgEnum.MoveNext())
{
Message current = msgEnum.Current;
Envelope msg = current.Body as Envelope;
// do something with the message
}
}
catch (Exception ex)
{
// handle exception
}
finally
{
if (msgEnum != null)
msgEnum.Close();
}
However, while another application is sending lots and lots of messages into the queue, i get the aforementioned exception.
I'm really confused as to why this is happening and what i need to do to make it work.
I also tried using GetAllMessages which resulted in the same exception.
Any help and/or explanations would be welcome.
edit:
the stack trace:
Error message: System.ServiceModel.FaultException`1[System.ServiceModel.ExceptionDetail]: An invalid handle was passed to the function. (Fault Detail is equal to An ExceptionDetail, likely created by IncludeExceptionDetailInFaults=true, whose value is:
System.Messaging.MessageQueueException: An invalid handle was passed to the function.
at System.Messaging.MessageEnumerator.MoveNext(TimeSpan timeout)
at Astea.AO.API.ControllerService.GetMessagesHeaders(String profileName, MessageQueueType queueType) in c:\Astea Alliance 11.0\Src\Framework\Astea.AO.API\Astea.AO.API.ControllerService\ControllerService.cs:line 170
at SyncInvokeGetMessagesHeaders(Object , Object[] , Object[] )
at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)).
Stack trace: at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
at System.Environment.get_StackTrace()
at APIConsoleWeb.Utils.Util.ReportError(String message) in c:\Astea Alliance 11.0\API.Controller\API.Controller\Utils\Util.cs:line 14
at APIConsoleWeb.Controllers.QueueMessagesController.GetMessagesHeaders(String profileName, MessageQueueType queueType) in c:\Astea Alliance 11.0\API.Controller\API.Controller\Controllers\QueueMessagesController.cs:line 37
at lambda_method(Closure , Object , Object[] )
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
at System.Web.Http.Tracing.Tracers.HttpActionDescriptorTracer.<>c__DisplayClass4.<ExecuteAsync>b__1()
at System.Web.Http.Tracing.ITraceWriterExtensions.TraceBeginEndAsync[TResult](ITraceWriter traceWriter, HttpRequestMessage request, String category, TraceLevel level, String operatorName, String operationName, Action`1 beginTrace, Func`1 execute, Action`2 endTrace, Action`1 errorTrace)
at System.Web.Http.Tracing.Tracers.HttpActionDescriptorTracer.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine)
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine& stateMachine)
at System.Web.Http.Controllers.ApiControllerActionInvoker.InvokeActionAsyncCore(HttpActionContext actionContext, CancellationToken cancellationToken)
at System.Web.Http.Controllers.ApiControllerActionInvoker.InvokeActionAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
at System.Web.Http.Tracing.Tracers.HttpActionInvokerTracer.<>c__DisplayClass4.<System.Web.Http.Controllers.IHttpActionInvoker.InvokeActionAsync>b__1()
at System.Web.Http.Tracing.ITraceWriterExtensions.TraceBeginEndAsync[TResult](ITraceWriter traceWriter, HttpRequestMessage request, String category, TraceLevel level, String operatorName, String operationName, Action`1 beginTrace, Func`1 execute, Action`2 endTrace, Action`1 errorTrace)
at System.Web.Http.Tracing.Tracers.HttpActionInvokerTracer.System.Web.Http.Controllers.IHttpActionInvoker.InvokeActionAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
at System.Web.Http.Controllers.ActionFilterResult.ActionInvoker.InvokeActionAsync()
at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine)
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine& stateMachine)
at System.Web.Http.Controllers.ActionFilterResult.ExecuteAsync(CancellationToken cancellationToken)
at System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)
at System.Web.Http.Tracing.Tracers.HttpControllerTracer.<ExecuteAsyncCore>d__5.MoveNext()
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine)
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine& stateMachine)
at System.Web.Http.Tracing.Tracers.HttpControllerTracer.ExecuteAsyncCore(HttpControllerContext controllerContext, CancellationToken cancellationToken)
at System.Web.Http.Tracing.Tracers.HttpControllerTracer.<>c__DisplayClass3.<System.Web.Http.Controllers.IHttpController.ExecuteAsync>b__0()
at System.Web.Http.Tracing.ITraceWriterExtensions.TraceBeginEndAsync[TResult](ITraceWriter traceWriter, HttpRequestMessage request, String category, TraceLevel level, String operatorName, String operationName, Action`1 beginTrace, Func`1 execute, Action`2 endTrace, Action`1 errorTrace)
at System.Web.Http.Tracing.Tracers.HttpControllerTracer.System.Web.Http.Controllers.IHttpController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)
at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine)
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine& stateMachine)
at System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpMessageInvoker.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Web.Http.Dispatcher.HttpRoutingDispatcher.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.DelegatingHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Web.Http.Tracing.Tracers.RequestMessageHandlerTracer.<>n__FabricatedMethod6(HttpRequestMessage , CancellationToken )
at System.Web.Http.Tracing.Tracers.RequestMessageHandlerTracer.<>c__DisplayClass4.<SendAsync>b__1()
at System.Web.Http.Tracing.ITraceWriterExtensions.TraceBeginEndAsync[TResult](ITraceWriter traceWriter, HttpRequestMessage request, String category, TraceLevel level, String operatorName, String operationName, Action`1 beginTrace, Func`1 execute, Action`2 endTrace, Action`1 errorTrace)
at System.Web.Http.Tracing.Tracers.RequestMessageHandlerTracer.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.DelegatingHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Web.Http.HttpServer.<>n__FabricatedMethod9(HttpRequestMessage , CancellationToken )
at System.Web.Http.HttpServer.<SendAsync>d__0.MoveNext()
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine)
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine& stateMachine)
at System.Web.Http.HttpServer.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpMessageInvoker.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Web.Http.WebHost.HttpControllerHandler.<ProcessRequestAsyncCore>d__0.MoveNext()
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine)
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine)
at System.Web.Http.WebHost.HttpControllerHandler.ProcessRequestAsyncCore(HttpContextBase contextBase)
at System.Web.Http.WebHost.HttpControllerHandler.ProcessRequestAsync(HttpContext context)
at System.Web.HttpTaskAsyncHandler.<>c__DisplayClass1.<System.Web.IHttpAsyncHandler.BeginProcessRequest>b__0()
at System.Web.TaskAsyncHelper.BeginTask(Func`1 taskFunc, AsyncCallback callback, Object state)
at System.Web.HttpTaskAsyncHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
at System.Web.HttpApplication.PipelineStepManager.ResumeSteps(Exception error)
at System.Web.HttpApplication.BeginProcessRequestNotification(HttpContext context, AsyncCallback cb)
at System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context)
at System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(IntPtr rootedObjectsPointer, IntPtr nativeRequestContext, IntPtr moduleData, Int32 flags)
at System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(IntPtr rootedObjectsPointer, IntPtr nativeRequestContext, IntPtr moduleData, Int32 flags)
at System.Web.Hosting.UnsafeIISMethods.MgdIndicateCompletion(IntPtr pHandler, RequestNotificationStatus& notificationStatus)
at System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(IntPtr rootedObjectsPointer, IntPtr nativeRequestContext, IntPtr moduleData, Int32 flags)
at System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(IntPtr rootedObjectsPointer, IntPtr nativeRequestContext, IntPtr moduleData, Int32 flags)

Related

Npgsql: What's the status of DB Transaction on Postgres DB side, when Rollback failed?

My postgres server version v12, Npgsql 7.0.0 used.
My question goes here: What's the status of DB Transaction on Postgres DB side, when Rollback a Npgsql.NpgsqlTransaction fails ?
And what's supposed to be done in that situation ?
Case 1:
|2023-01-16 08:51:28.355303 [Ingestion] ERROR [<obfuscated>Apps.<obfuscated>.Ingestion.Core.IngestionBootstrap_23] Run:
Npgsql.NpgsqlException (0x80004005): Received backend message NoData while expecting CommandCompleteMessage. Please file a bug.
at Npgsql.Util.Statics.ThrowIfMsgWrongType[T](IBackendMessage msg, NpgsqlConnector connector)
at Npgsql.Internal.NpgsqlConnector.ExecuteInternalCommand(Byte[] data, Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlTransaction.Rollback(Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlTransaction.Rollback()
at Microsoft.EntityFrameworkCore.Storage.RelationalTransaction.Rollback()
at <obfuscated>.Persistence.Repository.WriteRepository`2.Save(List`1 entities) in D:\repo\ptbuild\PT\Public\Apps\<obfuscated>\<obfuscated>.Persistence.Bulk\Repository\I<obfuscated>WriteRepository.cs:line 64
at <obfuscated><obfuscated>DivideAndRetrySaveStrategy`1.Save(List`1 entities, Int32 left, Int32 right, Dictionary`2 failed) in D:\repo\ptbuild\PT\Public\Apps\<obfuscated>\<obfuscated>.Ingestion\Ingest\DivideAndRetrySaveStrategy.cs:line 34
at <obfuscated><obfuscated>DivideAndRetrySaveStrategy`1.Save(List`1 entities) in D:\repo\ptbuild\PT\Public\Apps\<obfuscated>\<obfuscated>.Ingestion\Ingest\DivideAndRetrySaveStrategy.cs:line 29
at<obfuscated>.OrderIngest.Flush() in D:\repo\ptbuild\PT\Public\Apps\<obfuscated>\<obfuscated>.Ingestion\Ingest\OrderIngest.cs:line 62
at <obfuscated>Apps.<obfuscated>.Ingestion.Core.<obfuscated>MsgProcessor.FinishLoop() in <obfuscated><obfuscated>MsgProcessor.cs:line 276
at <obfuscated>Accessor.MonitoringAccessor.MonitoringAccessor.Refresh(IService fromService, DateTime timeStamp)
at <obfuscated>AccessLayer.Service.Core.DefaultService.Refresh(DateTime timeStamp) in D:\repo\ptbuild\PT\Public\AccessLayer.Service\Core\DefaultService.cs:line 297
at <obfuscated>Accessor.MonitoringAccessor.Service.MonitoringClientService.Refresh(DateTime now)
at <obfuscated>Apps.<obfuscated>.Ingestion.Core.IngestionBootstrap.Run() in <obfuscated>IngestionBootstrap.cs:line 137
Case 2:
|2023-01-13 14:01:37.154638 [Ingestion] ERROR [Microsoft.EntityFrameworkCore.Database.Command] Failed executing DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TEMP TABLE "#OrdersTemp2811321c" AS TABLE "Orders" WITH NO DATA;
|2023-01-13 14:01:37.163111 [Ingestion] ERROR [Microsoft.EntityFrameworkCore.Database.Transaction] An error occurred using a transaction.
|2023-01-13 14:01:37.163637 [Ingestion] ERROR [<obfuscated>Apps.<obfuscated>.Ingestion.Core.IngestionBootstrap_22] Run:
System.ObjectDisposedException: NpgsqlTransaction
---> Npgsql.NpgsqlException (0x80004005): Exception while reading from stream
---> System.TimeoutException: Timeout during reading attempt
at Npgsql.Internal.NpgsqlReadBuffer.<Ensure>g__EnsureLong|42_0(NpgsqlReadBuffer buffer, Int32 count, Boolean async, Boolean readingNotifications)
at Npgsql.Internal.NpgsqlConnector.<ReadMessage>g__ReadMessageLong|221_0(NpgsqlConnector connector, Boolean async, DataRowLoadingMode dataRowLoadingMode, Boolean readingNotifications, Boolean isReadingPrependedMessage)
at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming, CancellationToken cancellationToken)
at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming, CancellationToken cancellationToken)
at Npgsql.NpgsqlDataReader.NextResult()
at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlCommand.ExecuteNonQuery(Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlCommand.ExecuteNonQuery()
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQuery(RelationalCommandParameterObject parameterObject)
at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.ExecuteSqlRaw(DatabaseFacade databaseFacade, String sql, IEnumerable`1 parameters)
at EFCore.BulkExtensions.SQLAdapters.PostgreSql.PostgreSqlAdapter.MergeAsync[T](DbContext context, Type type, IList`1 entities, TableInfo tableInfo, OperationType operationType, Action`1 progress, Boolean isAsync, CancellationToken cancellationToken)
at EFCore.BulkExtensions.SQLAdapters.PostgreSql.PostgreSqlAdapter.Merge[T](DbContext context, Type type, IList`1 entities, TableInfo tableInfo, OperationType operationType, Action`1 progress)
at EFCore.BulkExtensions.DbContextBulkTransaction.Execute[T](DbContext context, Type type, IList`1 entities, OperationType operationType, BulkConfig bulkConfig, Action`1 progress)
at EFCore.BulkExtensions.DbContextBulkExtensions.BulkInsertOrUpdate[T](DbContext context, IList`1 entities, BulkConfig bulkConfig, Action`1 progress, Type type)
at <obfuscated>.Persistence.Repository.WriteRepository`2.Save(List`1 entities) in D:\repo\ptbuild\PT\Public\Apps\<obfuscated>\<obfuscated>.Persistence.Bulk\Repository\I<obfuscated>WriteRepository.cs:line 62
--- End of inner exception stack trace ---
at Npgsql.NpgsqlTransaction.CheckDisposed()
at Npgsql.NpgsqlTransaction.CheckReady()
at Npgsql.NpgsqlTransaction.Rollback(Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlTransaction.Rollback()
at Microsoft.EntityFrameworkCore.Storage.RelationalTransaction.Rollback()
at <obfuscated>.Persistence.Repository.WriteRepository`2.Save(List`1 entities) in D:\repo\ptbuild\PT\Public\Apps\<obfuscated>\<obfuscated>.Persistence.Bulk\Repository\I<obfuscated>WriteRepository.cs:line 62
at <obfuscated><obfuscated>DivideAndRetrySaveStrategy`1.Save(List`1 entities, Int32 left, Int32 right, Dictionary`2 failed) in D:\repo\ptbuild\PT\Public\Apps\<obfuscated>\<obfuscated>.Ingestion\Ingest\DivideAndRetrySaveStrategy.cs:line 34
at <obfuscated><obfuscated>DivideAndRetrySaveStrategy`1.Save(List`1 entities) in D:\repo\ptbuild\PT\Public\Apps\<obfuscated>\<obfuscated>.Ingestion\Ingest\DivideAndRetrySaveStrategy.cs:line 29
at<obfuscated>.OrderIngest.Flush() in D:\repo\ptbuild\PT\Public\Apps\<obfuscated>\<obfuscated>.Ingestion\Ingest\OrderIngest.cs:line 60
at <obfuscated>Apps.<obfuscated>.Ingestion.Core.<obfuscated>MsgProcessor.FinishLoop() in <obfuscated><obfuscated>MsgProcessor.cs:line 276
at <obfuscated>Accessor.MonitoringAccessor.MonitoringAccessor.Refresh(IService fromService, DateTime timeStamp)
at <obfuscated>AccessLayer.Service.Core.DefaultService.Refresh(DateTime timeStamp) in D:\repo\ptbuild\PT\Public\AccessLayer.Service\Core\DefaultService.cs:line 297
at <obfuscated>Accessor.MonitoringAccessor.Service.MonitoringClientService.Refresh(DateTime now)
at <obfuscated>Apps.<obfuscated>.Ingestion.Core.IngestionBootstrap.Run() in <obfuscated>IngestionBootstrap.cs:line 136
Many thanks!

Unity Android Build Issue - IL2CPP error (No further information)

I've been trying to make a build for Android with Unity, and I keep getting this error. I've reinstalled the Unity version and a few SDKs, but I can't figure anything out unfortunately. Any help would be appreciated!
Error: IL2CPP error (no further information about what managed code was being converted is available)
System.AggregateException: One or more errors occurred. (Found a method reference we cannot resolve to a method definition: UnityEngine.Touch[] UnityEngine.Input::get_touches())
---> System.InvalidOperationException: Found a method reference we cannot resolve to a method definition: UnityEngine.Touch[] UnityEngine.Input::get_touches()
at Unity.IL2CPP.DataModel.BuildLogic.MethodReferenceResolver.ResolveMethodReference(TypeContext context, UnderConstructionMethodReferenceRepository repository, CecilSourcedAssemblyData assemblyData, MethodReference methodReference, Dictionary`2 mapping)
at Unity.IL2CPP.DataModel.BuildLogic.MethodReferenceResolver.ResolveAssemblyMethodReferences(TypeContext context, UnderConstructionMethodReferenceRepository repository, CecilSourcedAssemblyData assemblyDef, ReadOnlyHashSet`1 methodReferences)
at Unity.IL2CPP.DataModel.BuildLogic.DataModelBuilder.<>c__DisplayClass15_0.<ResolveReferences>b__0(CecilSourcedAssemblyData data)
at System.Threading.Tasks.Parallel.<>c__DisplayClass33_0`2.<ForEachWorker>b__0(Int32 i)
at System.Threading.Tasks.Parallel.<>c__DisplayClass19_0`1.<ForWorker>b__1(RangeWorker& currentWorker, Int32 timeout, Boolean& replicationDelegateYieldedBeforeCompletion)
--- End of stack trace from previous location ---
at System.Threading.Tasks.Parallel.<>c__DisplayClass19_0`1.<ForWorker>b__1(RangeWorker& currentWorker, Int32 timeout, Boolean& replicationDelegateYieldedBeforeCompletion)
at System.Threading.Tasks.TaskReplicator.Replica`1.ExecuteAction(Boolean& yieldedBeforeCompletion)
at System.Threading.Tasks.TaskReplicator.Replica.Execute()
--- End of inner exception stack trace ---
at System.Threading.Tasks.TaskReplicator.Run[TState](ReplicatableUserAction`1 action, ParallelOptions options, Boolean stopOnFirstFailure)
at System.Threading.Tasks.Parallel.ForWorker[TLocal](Int32 fromInclusive, Int32 toExclusive, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Func`4 bodyWithLocal, Func`1 localInit, Action`1 localFinally)
--- End of stack trace from previous location ---
at System.Threading.Tasks.Parallel.ThrowSingleCancellationExceptionOrOtherException(ICollection exceptions, CancellationToken cancelToken, Exception otherException)
at System.Threading.Tasks.Parallel.ForWorker[TLocal](Int32 fromInclusive, Int32 toExclusive, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Func`4 bodyWithLocal, Func`1 localInit, Action`1 localFinally)
at System.Threading.Tasks.Parallel.ForEachWorker[TSource,TLocal](IList`1 list, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Action`3 bodyWithStateAndIndex, Func`4 bodyWithStateAndLocal, Func`5 bodyWithEverything, Func`1 localInit, Action`1 localFinally)
at System.Threading.Tasks.Parallel.ForEachWorker[TSource,TLocal](IEnumerable`1 source, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Action`3 bodyWithStateAndIndex, Func`4 bodyWithStateAndLocal, Func`5 bodyWithEverything, Func`1 localInit, Action`1 localFinally)
at System.Threading.Tasks.Parallel.ForEach[TSource](IEnumerable`1 source, Action`1 body)
at Unity.IL2CPP.DataModel.BuildLogic.Utils.ParallelHelpers.ForEach[TSource](IEnumerable`1 source, Action`1 func, Boolean enableSerial)
at Unity.IL2CPP.DataModel.BuildLogic.DataModelBuilder.Build()
at Unity.IL2CPP.Contexts.Components.DataModelComponent.Load(LoadSettings loadSettings, Boolean ownsTypeContext, Boolean ownsBuilder, DataModelBuilder& builder)
at Unity.IL2CPP.AssemblyConversion.Phases.InitializePhase.Run(AssemblyConversionContext context)
at Unity.IL2CPP.AssemblyConversion.Classic.ClassicConverter.Run(AssemblyConversionContext context)
at Unity.IL2CPP.AssemblyConversion.AssemblyConverter.ConvertAssemblies(AssemblyConversionInputData data, AssemblyConversionParameters parameters, AssemblyConversionInputDataForTopLevelAccess dataForTopLevel)

How to deploy aspnetcore app to ubuntu on digital ocean

After publishing my asp.net core 2.1 app to Digital Ocean on ubuntu server if i enter the server Ip in other to open the app in a browser I get this error:
Service Unavailable
The server is temporarily unable to service your request due to maintenance downtime or capacity problems. Please try again later.
Apache/version (Ubuntu) Server at Server_IP Port 80
From this Line:
Microsoft.AspNetCore.Identity.UserManager`1.FindByNameAsync(String userName)
at App_name.Data.ApplicationDbContext.CreateAdminAccount(IServiceProvider serviceProvider, IConfiguration configuration) in Data\ApplicationDbContext.cs:line
When i lunch the app locally i check if no user exist then CreateAdminAccount creates an admin user.
Am sure the app cannot make any migrations before the app lunches in other to create the admin user.
I want to know how to apply the migration to the database when the app launches.
If I check the application logs I get this error too:
at System.Net.Sockets.Socket.BeginConnectEx(EndPoint remoteEP, Boolean flowContext, AsyncCallback callback, Object state)
at System.Net.Sockets.Socket.UnsafeBeginConnect(EndPoint remoteEP, AsyncCallback callback, Object state, Boolean flowContext)
at System.Net.Sockets.Socket.BeginConnect(EndPoint remoteEP, AsyncCallback callback, Object state)
at System.Threading.Tasks.TaskFactory1.FromAsyncImpl[TArg1](Func4 beginMethod, Func2 endFunction, Action1 endAction, TArg1 arg1, Object state, TaskCreationOptions creationOptions)
at Npgsql.NpgsqlConnector.ConnectAsync(NpgsqlTimeout timeout, CancellationToken cancellationToken)
at Npgsql.NpgsqlConnector.RawOpen(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlConnector.Open(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
at Npgsql.ConnectorPool.AllocateLong(NpgsqlConnection conn, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlConnection.<>cDisplayClass32_0.<<Open>gOpenLong|0>d.MoveNext()
— End of stack trace from previous location where exception was thrown —
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnectionAsync(Boolean errorsExpected, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync(CancellationToken cancellationToken, Boolean errorsExpected)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable1.AsyncEnumerator.BufferlessMoveNext(DbContext _, Boolean buffer, CancellationToken cancellationToken)
at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func4 operation, Func4 verifySucceeded, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable1.AsyncEnumerator.MoveNext(CancellationToken cancellationToken)
at System.Linq.AsyncEnumerable.FirstOrDefault[TSource](IAsyncEnumerable1 source, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.TaskResultAsyncEnumerable1.Enumerator.MoveNext(CancellationToken cancellationToken)
at System.Linq.AsyncEnumerable.SelectEnumerableAsyncIterator2.MoveNextCore(CancellationToken cancellationToken)
at System.Linq.AsyncEnumerable.AsyncIterator1.MoveNext(CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.ExceptionInterceptor1.EnumeratorExceptionInterceptor.MoveNext(CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteSingletonAsyncQuery[TResult](QueryContext queryContext, Func2 compiledQuery, IDiagnosticsLogger1 logger, Type contextType)
at Microsoft.AspNetCore.Identity.UserManager1.FindByNameAsync(String userName)
at Appname.Data.ApplicationDbContext.CreateAdminAccount(IServiceProvider serviceProvider, IConfiguration configuration) in Data\ApplicationDbContext.cs:line 94
— End of inner exception stack trace —
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at Presscode.Startup.Configure(IApplicationBuilder app)
— End of stack trace from previous location where exception was thrown —
at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder app)
at Microsoft.AspNetCore.Hosting.Internal.AutoRequestServicesStartupFilter.<>cDisplayClass0_0.<Configure>b0(IApplicationBuilder builder)
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
—> (Inner Exception #0) System.Net.Sockets.SocketException (111): Connection refused
at System.Net.Sockets.Socket.BeginConnectEx(EndPoint remoteEP, Boolean flowContext, AsyncCallback callback, Object state)
at System.Net.Sockets.Socket.UnsafeBeginConnect(EndPoint remoteEP, AsyncCallback callback, Object state, Boolean flowContext)
at System.Net.Sockets.Socket.BeginConnect(EndPoint remoteEP, AsyncCallback callback, Object state)
at System.Threading.Tasks.TaskFactory1.FromAsyncImpl[TArg1](Func4 beginMethod, Func2 endFunction, Action1 endAction, TArg1 arg1, Object state, TaskCreationOptions creationOptions)
at Npgsql.NpgsqlConnector.ConnectAsync(NpgsqlTimeout timeout, CancellationToken cancellationToken)
at Npgsql.NpgsqlConnector.RawOpen(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlConnector.Open(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
at Npgsql.ConnectorPool.AllocateLong(NpgsqlConnection conn, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlConnection.<>cDisplayClass32_0.<<Open>gOpenLong|0>d.MoveNext()
— End of stack trace from previous location where exception was thrown —
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnectionAsync(Boolean errorsExpected, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync(CancellationToken cancellationToken, Boolean errorsExpected)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable1.AsyncEnumerator.BufferlessMoveNext(DbContext _, Boolean buffer, CancellationToken cancellationToken)
at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func4 operation, Func4 verifySucceeded, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable1.AsyncEnumerator.MoveNext(CancellationToken cancellationToken)
at System.Linq.AsyncEnumerable.FirstOrDefault[TSource](IAsyncEnumerable1 source, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.TaskResultAsyncEnumerable1.Enumerator.MoveNext(CancellationToken cancellationToken)
at System.Linq.AsyncEnumerable.SelectEnumerableAsyncIterator2.MoveNextCore(CancellationToken cancellationToken)
at System.Linq.AsyncEnumerable.AsyncIterator1.MoveNext(CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.ExceptionInterceptor1.EnumeratorExceptionInterceptor.MoveNext(CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteSingletonAsyncQuery[TResult](QueryContext queryContext, Func2 compiledQuery, IDiagnosticsLogger1 logger, Type contextType)
at Microsoft.AspNetCore.Identity.UserManager1.FindByNameAsync(String userName)
at AppName.Data.ApplicationDbContext.CreateAdminAccount(IServiceProvider serviceProvider, IConfiguration configuration) in Data\ApplicationDbContext.cs:line 94<—```

Getting HttpRequestExceptions: The response ended prematurely

For some reason, I'm getting a HttpRequestException with the message "The response ended prematurely. I'm creating about 500 tasks that use my RateLimitedHttpClient to make a request to a website so it can scrape it.
The exception is being thrown from the line return await response.Content.ReadAsStringAsync();.
Is it possible that with 500 tasks, each with ~20 pages to be downloaded and parsed (~11000 total), that I'm exceeding the capability of .Net's HttpClient?
public class SECScraper
{
public event EventHandler<ProgressChangedEventArgs> ProgressChangedEvent;
public SECScraper(EPSDownloader downloader, FinanceContext financeContext)
{
_downloader = downloader;
_financeContext = financeContext;
}
public void Download()
{
_numDownloaded = 0;
var companies = _financeContext.Companies.OrderBy(c => c.Name);
_interval = companies.Count() / 100;
var tasks = companies.Select(c => ScrapeSEC(c.CIK) ).ToList();
Task.WhenAll(tasks);
}
}
public class RateLimitedHttpClient : IHttpClient
{
public RateLimitedHttpClient(System.Net.Http.HttpClient client)
{
_client = client;
_client.Timeout = TimeSpan.FromMinutes(30);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
}
public async Task<string> ReadAsync(string url)
{
if (!_sw.IsRunning)
_sw.Start();
await Delay();
using var response = await _client.GetAsync(url);
return await response.Content.ReadAsStringAsync();
}
private async Task Delay()
{
var totalElapsed = GetTimeElapsedSinceLastRequest();
while (totalElapsed < MinTimeBetweenRequests)
{
await Task.Delay(MinTimeBetweenRequests - totalElapsed);
totalElapsed = GetTimeElapsedSinceLastRequest();
};
_timeElapsedOfLastHttpRequest = (int)_sw.Elapsed.TotalMilliseconds;
}
private int GetTimeElapsedSinceLastRequest()
{
return (int)_sw.Elapsed.TotalMilliseconds - _timeElapsedOfLastHttpRequest;
}
private readonly System.Net.Http.HttpClient _client;
private readonly Stopwatch _sw = new Stopwatch();
private int _timeElapsedOfLastHttpRequest;
private const int MinTimeBetweenRequests = 100;
}
It appears that I am getting a few HttpRequestExceptions here.
System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.IO.IOException: The response ended prematurely.
at System.Net.Http.HttpConnection.FillAsync()
at System.Net.Http.HttpConnection.ReadNextResponseHeaderLineAsync(Boolean foldedHeadersAllowed)
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)
at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
at POLib.Http.RateLimitedHttpClient.ReadAsync(String url) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\Http\RateLimitedHttpClient.cs:line 23
at POLib.SECScraper.EPS.EPSDownloader.GetReportLinks(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\EPS\EPSDownloader.cs:line 65
at POLib.SECScraper.EPS.EPSDownloader.GetEPSData(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\EPS\EPSDownloader.cs:line 19
at POLib.SECScraper.SECScraper.ScrapeSEC(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\SECScraper.cs:line 40
System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.IO.IOException: Unable to read data from the transport connection: An established connection was aborted by the software in your host machine.. ---> System.Net.Sockets.SocketException (10053): An established connection was aborted by the software in your host machine.
--- End of inner exception stack trace ---
at System.Net.Security.SslStream.<FillBufferAsync>g__InternalFillBufferAsync|215_0[TReadAdapter](TReadAdapter adap, ValueTask`1 task, Int32 min, Int32 initial)
at System.Net.Security.SslStream.ReadAsyncInternal[TReadAdapter](TReadAdapter adapter, Memory`1 buffer)
at System.Net.Http.HttpConnection.FillAsync()
at System.Net.Http.HttpConnection.ReadNextResponseHeaderLineAsync(Boolean foldedHeadersAllowed)
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)
at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
at POLib.Http.RateLimitedHttpClient.ReadAsync(String url) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\Http\RateLimitedHttpClient.cs:line 23
at POLib.SECScraper.EPS.EPSDownloader.GetReportLinks(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\EPS\EPSDownloader.cs:line 65
at POLib.SECScraper.EPS.EPSDownloader.GetEPSData(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\EPS\EPSDownloader.cs:line 19
at POLib.SECScraper.SECScraper.ScrapeSEC(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\SECScraper.cs:line 40
System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.IO.IOException: Unable to read data from the transport connection: An established connection was aborted by the software in your host machine.. ---> System.Net.Sockets.SocketException (10053): An established connection was aborted by the software in your host machine.
--- End of inner exception stack trace ---
at System.Net.Security.SslStream.<WriteSingleChunk>g__CompleteAsync|210_1[TWriteAdapter](ValueTask writeTask, Byte[] bufferToReturn)
at System.Net.Security.SslStream.WriteAsyncInternal[TWriteAdapter](TWriteAdapter writeAdapter, ReadOnlyMemory`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)
at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
at POLib.Http.RateLimitedHttpClient.ReadAsync(String url) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\Http\RateLimitedHttpClient.cs:line 23
at POLib.SECScraper.EPS.EPSDownloader.GetReportLinks(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\EPS\EPSDownloader.cs:line 65
at POLib.SECScraper.EPS.EPSDownloader.GetEPSData(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\EPS\EPSDownloader.cs:line 19
at POLib.SECScraper.SECScraper.ScrapeSEC(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\SECScraper.cs:line 40
System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.IO.IOException: The response ended prematurely.
at System.Net.Http.HttpConnection.FillAsync()
at System.Net.Http.HttpConnection.ReadNextResponseHeaderLineAsync(Boolean foldedHeadersAllowed)
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)
at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
at POLib.Http.RateLimitedHttpClient.ReadAsync(String url) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\Http\RateLimitedHttpClient.cs:line 23
at POLib.SECScraper.EPS.EPSDownloader.GetReportLinks(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\EPS\EPSDownloader.cs:line 65
at POLib.SECScraper.EPS.EPSDownloader.GetEPSData(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\EPS\EPSDownloader.cs:line 19
at POLib.SECScraper.SECScraper.ScrapeSEC(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\SECScraper.cs:line 40
System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.IO.IOException: The response ended prematurely.
> at System.Net.Http.HttpConnection.FillAsync()
> at System.Net.Http.HttpConnection.ReadNextResponseHeaderLineAsync(Boolean foldedHeadersAllowed)
> 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)
> at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
> at POLib.Http.RateLimitedHttpClient.ReadAsync(String url) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\Http\RateLimitedHttpClient.cs:line 23
> at POLib.SECScraper.EPS.EPSDownloader.GetReportLinks(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\EPS\EPSDownloader.cs:line 65
> at POLib.SECScraper.EPS.EPSDownloader.GetEPSData(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\EPS\EPSDownloader.cs:line 19
> at POLib.SECScraper.SECScraper.ScrapeSEC(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\SECScraper.cs:line 40
> System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.IO.IOException: Unable to read data from the transport connection: An established connection was aborted by the software in your host machine.. ---> System.Net.Sockets.SocketException (10053): An established connection was aborted by the software in your host machine.
> --- End of inner exception stack trace ---
> at System.Net.Security.SslStream.<FillBufferAsync>g__InternalFillBufferAsync|215_0[TReadAdapter](TReadAdapter adap, ValueTask`1 task, Int32 min, Int32 initial)
> at System.Net.Security.SslStream.ReadAsyncInternal[TReadAdapter](TReadAdapter adapter, Memory`1 buffer)
> at System.Net.Http.HttpConnection.FillAsync()
> at System.Net.Http.HttpConnection.ReadNextResponseHeaderLineAsync(Boolean foldedHeadersAllowed)
> 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)
> at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
> at POLib.Http.RateLimitedHttpClient.ReadAsync(String url) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\Http\RateLimitedHttpClient.cs:line 23
> at POLib.SECScraper.EPS.EPSDownloader.GetReportLinks(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\EPS\EPSDownloader.cs:line 65
> at POLib.SECScraper.EPS.EPSDownloader.GetEPSData(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\EPS\EPSDownloader.cs:line 19
> at POLib.SECScraper.SECScraper.ScrapeSEC(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\SECScraper.cs:line 40
> System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.IO.IOException: Unable to read data from the transport connection: An established connection was aborted by the software in your host machine.. ---> System.Net.Sockets.SocketException (10053): An established connection was aborted by the software in your host machine.
> --- End of inner exception stack trace ---
> at System.Net.Security.SslStream.<WriteSingleChunk>g__CompleteAsync|210_1[TWriteAdapter](ValueTask writeTask, Byte[] bufferToReturn)
> at System.Net.Security.SslStream.WriteAsyncInternal[TWriteAdapter](TWriteAdapter writeAdapter, ReadOnlyMemory`1 buffer)
System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception. ---> System.IO.IOException: Authentication failed because the remote party has closed the transport stream.
at System.Net.Security.SslStream.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.ProcessAuthentication(LazyAsyncResult lazyResult, CancellationToken cancellationToken)
at System.Net.Security.SslStream.BeginAuthenticateAsClient(SslClientAuthenticationOptions sslClientAuthenticationOptions, CancellationToken cancellationToken, AsyncCallback asyncCallback, Object asyncState)
at System.Net.Security.SslStream.<>c.<AuthenticateAsClientAsync>b__65_0(SslClientAuthenticationOptions arg1, CancellationToken arg2, AsyncCallback callback, Object state)
at System.Threading.Tasks.TaskFactory`1.FromAsyncImpl[TArg1,TArg2](Func`5 beginMethod, Func`2 endFunction, Action`1 endAction, TArg1 arg1, TArg2 arg2, Object state, TaskCreationOptions creationOptions)
at System.Threading.Tasks.TaskFactory.FromAsync[TArg1,TArg2](Func`5 beginMethod, Action`1 endMethod, TArg1 arg1, TArg2 arg2, Object state, TaskCreationOptions creationOptions)
at System.Threading.Tasks.TaskFactory.FromAsync[TArg1,TArg2](Func`5 beginMethod, Action`1 endMethod, TArg1 arg1, TArg2 arg2, Object state)
at System.Net.Security.SslStream.AuthenticateAsClientAsync(SslClientAuthenticationOptions sslClientAuthenticationOptions, CancellationToken cancellationToken)
at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)
at System.Threading.Tasks.ValueTask`1.get_Result()
at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean allowHttp2, CancellationToken cancellationToken)
at System.Threading.Tasks.ValueTask`1.get_Result()
at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Threading.Tasks.ValueTask`1.get_Result()
at System.Net.Http.HttpConnectionPool.GetHttpConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Threading.Tasks.ValueTask`1.get_Result()
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.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
at POLib.Http.RateLimitedHttpClient.ReadAsync(String url) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\Http\RateLimitedHttpClient.cs:line 23
at POLib.SECScraper.EPS.EPSDownloader.GetReportLinks(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\EPS\EPSDownloader.cs:line 65
at POLib.SECScraper.EPS.EPSDownloader.GetEPSData(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\EPS\EPSDownloader.cs:line 19
at POLib.SECScraper.SECScraper.ScrapeSEC(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\SECScraper.cs:line 40
> at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)
System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception. ---> System.IO.IOException: Authentication failed because the remote party has closed the transport stream.
at System.Net.Security.SslStream.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.ProcessAuthentication(LazyAsyncResult lazyResult, CancellationToken cancellationToken)
at System.Net.Security.SslStream.BeginAuthenticateAsClient(SslClientAuthenticationOptions sslClientAuthenticationOptions, CancellationToken cancellationToken, AsyncCallback asyncCallback, Object asyncState)
at System.Net.Security.SslStream.<>c.<AuthenticateAsClientAsync>b__65_0(SslClientAuthenticationOptions arg1, CancellationToken arg2, AsyncCallback callback, Object state)
at System.Threading.Tasks.TaskFactory`1.FromAsyncImpl[TArg1,TArg2](Func`5 beginMethod, Func`2 endFunction, Action`1 endAction, TArg1 arg1, TArg2 arg2, Object state, TaskCreationOptions creationOptions)
at System.Threading.Tasks.TaskFactory.FromAsync[TArg1,TArg2](Func`5 beginMethod, Action`1 endMethod, TArg1 arg1, TArg2 arg2, Object state, TaskCreationOptions creationOptions)
at System.Threading.Tasks.TaskFactory.FromAsync[TArg1,TArg2](Func`5 beginMethod, Action`1 endMethod, TArg1 arg1, TArg2 arg2, Object state)
at System.Net.Security.SslStream.AuthenticateAsClientAsync(SslClientAuthenticationOptions sslClientAuthenticationOptions, CancellationToken cancellationToken)
at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)
at System.Threading.Tasks.ValueTask`1.get_Result()
at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean allowHttp2, CancellationToken cancellationToken)
at System.Threading.Tasks.ValueTask`1.get_Result()
at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Threading.Tasks.ValueTask`1.get_Result()
at System.Net.Http.HttpConnectionPool.GetHttpConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Threading.Tasks.ValueTask`1.get_Result()
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.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
at POLib.Http.RateLimitedHttpClient.ReadAsync(String url) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\Http\RateLimitedHttpClient.cs:line 23
at POLib.SECScraper.EPS.EPSDownloader.GetReportLinks(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\EPS\EPSDownloader.cs:line 65
at POLib.SECScraper.EPS.EPSDownloader.GetEPSData(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\EPS\EPSDownloader.cs:line 19
at POLib.SECScraper.SECScraper.ScrapeSEC(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\SECScraper.cs:line 40
> --- End of inner exception stack trace ---
System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception. ---> System.IO.IOException: Authentication failed because the remote party has closed the transport stream.
at System.Net.Security.SslStream.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.ProcessAuthentication(LazyAsyncResult lazyResult, CancellationToken cancellationToken)
at System.Net.Security.SslStream.BeginAuthenticateAsClient(SslClientAuthenticationOptions sslClientAuthenticationOptions, CancellationToken cancellationToken, AsyncCallback asyncCallback, Object asyncState)
at System.Net.Security.SslStream.<>c.<AuthenticateAsClientAsync>b__65_0(SslClientAuthenticationOptions arg1, CancellationToken arg2, AsyncCallback callback, Object state)
at System.Threading.Tasks.TaskFactory`1.FromAsyncImpl[TArg1,TArg2](Func`5 beginMethod, Func`2 endFunction, Action`1 endAction, TArg1 arg1, TArg2 arg2, Object state, TaskCreationOptions creationOptions)
at System.Threading.Tasks.TaskFactory.FromAsync[TArg1,TArg2](Func`5 beginMethod, Action`1 endMethod, TArg1 arg1, TArg2 arg2, Object state, TaskCreationOptions creationOptions)
at System.Threading.Tasks.TaskFactory.FromAsync[TArg1,TArg2](Func`5 beginMethod, Action`1 endMethod, TArg1 arg1, TArg2 arg2, Object state)
at System.Net.Security.SslStream.AuthenticateAsClientAsync(SslClientAuthenticationOptions sslClientAuthenticationOptions, CancellationToken cancellationToken)
at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)
at System.Threading.Tasks.ValueTask`1.get_Result()
at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean allowHttp2, CancellationToken cancellationToken)
at System.Threading.Tasks.ValueTask`1.get_Result()
at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Threading.Tasks.ValueTask`1.get_Result()
at System.Net.Http.HttpConnectionPool.GetHttpConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Threading.Tasks.ValueTask`1.get_Result()
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.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
at POLib.Http.RateLimitedHttpClient.ReadAsync(String url) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\Http\RateLimitedHttpClient.cs:line 23
at POLib.SECScraper.EPS.EPSDownloader.GetReportLinks(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\EPS\EPSDownloader.cs:line 65
at POLib.SECScraper.EPS.EPSDownloader.GetEPSData(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\EPS\EPSDownloader.cs:line 19
at POLib.SECScraper.SECScraper.ScrapeSEC(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\SECScraper.cs:line 40
You just need to keep digging. The exception "The response ended prematurely" isn't the root cause. Keep digging into the inner exceptions until you find the last one. You'll find this:
System.IO.IOException: Authentication failed because the remote party has closed the transport stream.
So it's not about your code. It seems the server you're hitting either can't handle the load, or is intentionally dropping your requests because you're hitting it too hard.
Also make sure the base address is correct
is it 'http' or 'https'
when you construct base address
In my case the problem was in the HTTP version. When I switched to HTTP/2.0 the exception was gone and the request completed successfully.
var message = new HttpRequestMessage(HttpMethod.Get, url) { Version = new Version(2, 0) };
var request = await httpClient.SendAsync(message);
I added the host and agent to the header, the problem was fixed.
var request = (HttpWebRequest)WebRequest.Create(url);
request.Host = request.RequestUri.Host; //"example.com"
request.UserAgent = "Dotnet";
In my case, a .netcore 3.1 application, it was solved by adding this line of code:
public void ConfigureServices(IServiceCollection services)
{
// Enable support for unencrypted HTTP2
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
}

SimpleInjector and Microsoft Webhook ASP.Net Webhooks

We had been successfully using the Microsoft ASP.Net Webhooks (specifically the Stripe one) in our WebAPI 2 project with Ninject. Recently we migrated to SimpleInjector and while everything else went well, we cannot get this webhook processor to work. It keeps throwing the following exception: System.MissingMethodException: 'No parameterless constructor defined for this object.'
The relevant stack traces are:
mscorlib.dll!System.RuntimeType.CreateInstanceSlow(bool publicOnly, bool skipCheckThis, bool fillCache, ref System.Threading.StackCrawlMark stackMark) Unknown
mscorlib.dll!System.Activator.CreateInstance(System.Type type, bool nonPublic) Unknown
mscorlib.dll!System.Activator.CreateInstance(System.Type type) Unknown
Microsoft.AspNet.WebHooks.Common.dll!Microsoft.AspNet.WebHooks.Utilities.TypeUtilities.GetInstances<Microsoft.AspNet.WebHooks.IWebHookHandler>(System.Collections.Generic.IEnumerable<System.Reflection.Assembly> assemblies, System.Func<System.Type, bool> predicate) Unknown
Microsoft.AspNet.WebHooks.Receivers.dll!Microsoft.AspNet.WebHooks.ReceiverServices.GetHandlers() Unknown
Microsoft.AspNet.WebHooks.Receivers.dll!Microsoft.AspNet.WebHooks.DependencyScopeExtensions.GetHandlers(System.Web.Http.Dependencies.IDependencyScope services = {SimpleInjector.Integration.WebApi.SimpleInjectorWebApiDependencyResolver}) Unknown
Microsoft.AspNet.WebHooks.Receivers.dll!Microsoft.AspNet.WebHooks.WebHookReceiver.ExecuteWebHookAsync(string id = "", System.Web.Http.Controllers.HttpRequestContext context = {System.Web.Http.WebHost.WebHostHttpRequestContext}, System.Net.Http.HttpRequestMessage request = {System.Net.Http.HttpRequestMessage}, System.Collections.Generic.IEnumerable<string> actions = {string[1]}, object data = {Newtonsoft.Json.Linq.JObject}) Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.__Canon>.Start<Microsoft.AspNet.WebHooks.WebHookReceiver.<ExecuteWebHookAsync>d__22>(ref Microsoft.AspNet.WebHooks.WebHookReceiver.<ExecuteWebHookAsync>d__22 stateMachine) Unknown
Microsoft.AspNet.WebHooks.Receivers.dll!Microsoft.AspNet.WebHooks.WebHookReceiver.ExecuteWebHookAsync(string id, System.Web.Http.Controllers.HttpRequestContext context, System.Net.Http.HttpRequestMessage request, System.Collections.Generic.IEnumerable<string> actions, object data) Unknown
Microsoft.AspNet.WebHooks.Receivers.Stripe.dll!Microsoft.AspNet.WebHooks.StripeWebHookReceiver.ReceiveAsync(string id = "", System.Web.Http.Controllers.HttpRequestContext context = {System.Web.Http.WebHost.WebHostHttpRequestContext}, System.Net.Http.HttpRequestMessage request = {System.Net.Http.HttpRequestMessage}) Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.__Canon>.Start<Microsoft.AspNet.WebHooks.StripeWebHookReceiver.<ReceiveAsync>d__15>(ref Microsoft.AspNet.WebHooks.StripeWebHookReceiver.<ReceiveAsync>d__15 stateMachine) Unknown
Microsoft.AspNet.WebHooks.Receivers.Stripe.dll!Microsoft.AspNet.WebHooks.StripeWebHookReceiver.ReceiveAsync(string id, System.Web.Http.Controllers.HttpRequestContext context, System.Net.Http.HttpRequestMessage request) Unknown
Microsoft.AspNet.WebHooks.Receivers.dll!Microsoft.AspNet.WebHooks.Controllers.WebHookReceiversController.ProcessWebHook(string webHookReceiver = "stripe", string id = "") Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.__Canon>.Start<Microsoft.AspNet.WebHooks.Controllers.WebHookReceiversController.<ProcessWebHook>d__3>(ref Microsoft.AspNet.WebHooks.Controllers.WebHookReceiversController.<ProcessWebHook>d__3 stateMachine) Unknown
Microsoft.AspNet.WebHooks.Receivers.dll!Microsoft.AspNet.WebHooks.Controllers.WebHookReceiversController.ProcessWebHook(string webHookReceiver, string id) Unknown
[Lightweight Function]
System.Web.Http.dll!System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.GetExecutor.AnonymousMethod__8(object instance, object[] methodParameters) Unknown
System.Web.Http.dll!System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(System.Web.Http.Controllers.HttpControllerContext controllerContext, System.Collections.Generic.IDictionary<string, object> arguments, System.Threading.CancellationToken cancellationToken) Unknown
System.Web.Http.dll!System.Web.Http.Controllers.ApiControllerActionInvoker.InvokeActionAsyncCore(System.Web.Http.Controllers.HttpActionContext actionContext = {System.Web.Http.Controllers.HttpActionContext}, System.Threading.CancellationToken cancellationToken = IsCancellationRequested = false) Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.__Canon>.Start<System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0>(ref System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0 stateMachine) Unknown
System.Web.Http.dll!System.Web.Http.Controllers.ApiControllerActionInvoker.InvokeActionAsyncCore(System.Web.Http.Controllers.HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken) Unknown
System.Web.Http.dll!System.Web.Http.Controllers.ApiControllerActionInvoker.InvokeActionAsync(System.Web.Http.Controllers.HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken) Unknown
System.Web.Http.dll!System.Web.Http.Controllers.ActionFilterResult.ExecuteAsync(System.Threading.CancellationToken cancellationToken = IsCancellationRequested = false) Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.__Canon>.Start<System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2>(ref System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2 stateMachine) Unknown
System.Web.Http.dll!System.Web.Http.Controllers.ActionFilterResult.ExecuteAsync(System.Threading.CancellationToken cancellationToken) Unknown
System.Web.Http.dll!System.Web.Http.ApiController.ExecuteAsync(System.Web.Http.Controllers.HttpControllerContext controllerContext, System.Threading.CancellationToken cancellationToken) Unknown
System.Web.Http.dll!System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync(System.Net.Http.HttpRequestMessage request = {System.Net.Http.HttpRequestMessage}, System.Threading.CancellationToken cancellationToken = IsCancellationRequested = false) Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.__Canon>.Start<System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1>(ref System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1 stateMachine) Unknown
System.Web.Http.dll!System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown
System.Net.Http.dll!System.Net.Http.HttpMessageInvoker.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown
System.Web.Http.dll!System.Web.Http.Dispatcher.HttpRoutingDispatcher.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown
System.Net.Http.dll!System.Net.Http.DelegatingHandler.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown
System.Web.Http.Cors.dll!System.Web.Http.Cors.CorsMessageHandler.SendAsync(System.Net.Http.HttpRequestMessage request = {System.Net.Http.HttpRequestMessage}, System.Threading.CancellationToken cancellationToken = IsCancellationRequested = false) Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.__Canon>.Start<System.Web.Http.Cors.CorsMessageHandler.<SendAsync>d__0>(ref System.Web.Http.Cors.CorsMessageHandler.<SendAsync>d__0 stateMachine) Unknown
System.Web.Http.Cors.dll!System.Web.Http.Cors.CorsMessageHandler.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown
System.Net.Http.dll!System.Net.Http.DelegatingHandler.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown
System.Web.Http.dll!System.Web.Http.HttpServer.SendAsync(System.Net.Http.HttpRequestMessage request = {System.Net.Http.HttpRequestMessage}, System.Threading.CancellationToken cancellationToken = IsCancellationRequested = false) Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.__Canon>.Start<System.Web.Http.HttpServer.<SendAsync>d__0>(ref System.Web.Http.HttpServer.<SendAsync>d__0 stateMachine) Unknown
System.Web.Http.dll!System.Web.Http.HttpServer.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown
System.Net.Http.dll!System.Net.Http.HttpMessageInvoker.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown
System.Web.Http.WebHost.dll!System.Web.Http.WebHost.HttpControllerHandler.ProcessRequestAsyncCore(System.Web.HttpContextBase contextBase = {System.Web.HttpContextWrapper}) Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start<System.Web.Http.WebHost.HttpControllerHandler.<ProcessRequestAsyncCore>d__0>(ref System.Web.Http.WebHost.HttpControllerHandler.<ProcessRequestAsyncCore>d__0 stateMachine) Unknown
System.Web.Http.WebHost.dll!System.Web.Http.WebHost.HttpControllerHandler.ProcessRequestAsyncCore(System.Web.HttpContextBase contextBase) Unknown
System.Web.dll!System.Web.TaskAsyncHelper.BeginTask(System.Func<System.Threading.Tasks.Task> taskFunc, System.AsyncCallback callback, object state = null) Unknown
System.Web.dll!System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() Unknown
System.Web.dll!System.Web.HttpApplication.ExecuteStep(System.Web.HttpApplication.IExecutionStep step = {System.Web.HttpApplication.CallHandlerExecutionStep}, ref bool completedSynchronously = false) Unknown
System.Web.dll!System.Web.HttpApplication.PipelineStepManager.ResumeSteps(System.Exception error) Unknown
System.Web.dll!System.Web.HttpApplication.BeginProcessRequestNotification(System.Web.HttpContext context, System.AsyncCallback cb) Unknown
System.Web.dll!System.Web.HttpRuntime.ProcessRequestNotificationPrivate(System.Web.Hosting.IIS7WorkerRequest wr = {System.Web.Hosting.IIS7WorkerRequest}, System.Web.HttpContext context = {System.Web.HttpContext}) Unknown
System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext = 0x000002226c0521f0, System.IntPtr moduleData, int flags) Unknown
System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags) Unknown
[Native to Managed Transition]
[Managed to Native Transition]
System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags) Unknown
System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags) Unknown
[AppDomain Transition]
And
System.MissingMethodException: No parameterless constructor defined for this object.
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.Activator.CreateInstance(Type type)
at Microsoft.AspNet.WebHooks.Utilities.TypeUtilities.GetInstances[T](IEnumerable`1 assemblies, Func`2 predicate)
at Microsoft.AspNet.WebHooks.ReceiverServices.GetHandlers()
at Microsoft.AspNet.WebHooks.DependencyScopeExtensions.GetHandlers(IDependencyScope services)
at Microsoft.AspNet.WebHooks.WebHookReceiver.<ExecuteWebHookAsync>d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNet.WebHooks.StripeWebHookReceiver.<ReceiveAsync>d__15.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNet.WebHooks.Controllers.WebHookReceiversController.<ProcessWebHook>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Threading.Tasks.TaskHelpersExtensions.<CastToObject>d__3`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()
Our global.asax looks like this:
var container = new Container();
container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();
container.Options.PropertySelectionBehavior = new
InjectPropertySelectionBehavior();
// Register our stuff
container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
container.RegisterWebApiControllers(GlobalConfiguration.Configuration);
container.Verify();
GlobalConfiguration.Configuration.DependencyResolver = new
SimpleInjectorWebApiDependencyResolver(container);
DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
we're registering the WebHook handler like this:
container.Register<IWebHookHandler, StripeWebhookHandler>(Lifestyle.Singleton);
Has anyone gotten this to work with SimpleInjector? Or have any ideas what might be wrong?
Solution:
IWebhookHandler needs registered as a collection, so doing this:
container.Collection.Append(typeof(IWebHookHandler), typeof(StripeWebhookHandler));
instead of:
container.Register<IWebHookHandler, StripeWebhookHandler>(Lifestyle.Singleton);
was the trick!
I figured this out by stepping into the source of both the Microsoft Webhook assembly and SimpleInjector and found that when the Webhook assembly asked for all instances of type IWebhookHandler, SimpleInjector, in its GetServices implementation was trying to find all IEnumerable<IWebhookHandler> instead and so was coming up with nothing.
These kind of exceptions are thrown when trying to resolve a dependency that has parameter constructors but one or more of the parameters has not been registered and thus cannot be resolved, resulting in a fall back to a parameter-less constructor which in certain cases are absent.
Verify that you have registered all the components needed by WebHooks to work.

Categories