Self hosting nancy with razor returns empty body - c#

Self hosting nancy with razor returns empty body.
I'm trying to self-host nancy in a console application with razor views, however I'm getting an empty body back.
It does work when running in IIS.
What I did:
I added all the appropriate razor configuration and build providers to the App.Config
I added a custom static root path provider, which seems to be configured well, as static files are served without a problem:
protected override IRootPathProvider RootPathProvider
{
get
{
if (ConfigurationManager.AppSettings["RootPath"].HasValue())
{
var path = Path.Combine(new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.FullName, ConfigurationManager.AppSettings["RootPath"]);
return new StaticRootPathProvider(path);
}
return new DefaultRootPathProvider();
}
}
The razor view is found an being compiled, because when I add invalid code to the view, I do get a razor compiler error
When I debug with all exceptions caught, I get an exception on serving the page:
A first chance exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in Nancy.dll
Additional information: Cannot convert type 'Nancy.Responses.Negotiation.Negotiator' to 'Nancy.Response'
Nancy.dll!Nancy.Routing.DefaultRouteInvoker.CastResultToResponse(dynamic result) Unknown
Nancy.dll!Nancy.Routing.DefaultRouteInvoker.InvokeRouteWithStrategy(dynamic result, Nancy.NancyContext context) Unknown
Nancy.dll!Nancy.Routing.DefaultRouteInvoker.Invoke.AnonymousMethod__5(System.Threading.Tasks.Task completedTask) Unknown
Nancy.dll!Nancy.Helpers.TaskHelpers.WhenCompleted(System.Threading.Tasks.Task task, System.Action> onComplete, System.Action> onFaulted, bool execSync) Unknown
Nancy.dll!Nancy.Routing.DefaultRouteInvoker.Invoke(Nancy.Routing.Route route, System.Threading.CancellationToken cancellationToken, Nancy.DynamicDictionary parameters, Nancy.NancyContext context) Unknown
Nancy.dll!Nancy.Routing.DefaultRequestDispatcher.Dispatch.AnonymousMethod__0(System.Threading.Tasks.Task completedTask) Unknown
Nancy.dll!Nancy.Helpers.TaskHelpers.WhenCompleted(System.Threading.Tasks.Task task, System.Action> onComplete, System.Action> onFaulted, bool execSync) Unknown
Nancy.dll!Nancy.Routing.DefaultRequestDispatcher.Dispatch(Nancy.NancyContext context, System.Threading.CancellationToken cancellationToken) Unknown
Nancy.dll!Nancy.NancyEngine.InvokeRequestLifeCycle.AnonymousMethod__9(System.Threading.Tasks.Task t) Unknown
Nancy.dll!Nancy.Helpers.TaskHelpers.WhenCompleted(System.Threading.Tasks.Task task, System.Action> onComplete, System.Action> onFaulted, bool execSync) Unknown
Nancy.dll!Nancy.NancyEngine.InvokeRequestLifeCycle(Nancy.NancyContext context, System.Threading.CancellationToken cancellationToken, Nancy.Bootstrapper.IPipelines pipelines) Unknown
Nancy.dll!Nancy.NancyEngine.HandleRequest(Nancy.Request request, System.Func preRequest, System.Threading.CancellationToken cancellationToken) Unknown
Nancy.dll!Nancy.NancyEngineExtensions.HandleRequest(Nancy.INancyEngine nancyEngine, Nancy.Request request, System.Func preRequest) Unknown
Nancy.dll!Nancy.NancyEngineExtensions.HandleRequest(Nancy.INancyEngine nancyEngine, Nancy.Request request) Unknown
Nancy.Hosting.Self.dll!Nancy.Hosting.Self.NancyHost.Process(System.Net.HttpListenerContext ctx) Unknown
Nancy.Hosting.Self.dll!Nancy.Hosting.Self.NancyHost.GotCallback(System.IAsyncResult ar) Unknown
System.dll!System.Net.LazyAsyncResult.Complete(System.IntPtr userToken) Unknown
System.dll!System.Net.LazyAsyncResult.ProtectedInvokeCallback(object result, System.IntPtr userToken) Unknown
System.dll!System.Net.ListenerAsyncResult.IOCompleted(System.Net.ListenerAsyncResult asyncResult, uint errorCode, uint numBytes) Unknown
System.dll!System.Net.ListenerAsyncResult.WaitCallback(uint errorCode, uint numBytes, System.Threading.NativeOverlapped* nativeOverlapped) Unknown
mscorlib.dll!System.Threading._IOCompletionCallback.PerformIOCompletionCallback(uint errorCode, uint numBytes, System.Threading.NativeOverlapped* pOVERLAP) Unknown
Then followed by a ArgumentNullException:
System.ArgumentNullException occurred
Message: A first chance exception of type 'System.ArgumentNullException' occurred in System.Web.dll
Additional information: Value cannot be null.
System.Web.dll!System.Web.HttpContextWrapper.HttpContextWrapper(System.Web.HttpContext httpContext) Unknown
System.Web.Optimization.dll!System.Web.Optimization.Styles.Context.get() Unknown
System.Web.Optimization.dll!System.Web.Optimization.Styles.RenderFormat(string tagFormat, string[] paths) Unknown
Temp_bfd13a3e77214eca9b1ce8f1a37d244d.dll!RazorOutput.RazorView.Execute() Unknown
Nancy.ViewEngines.Razor.dll!Nancy.ViewEngines.Razor.NancyRazorViewBase.ExecuteView(string body, System.Collections.Generic.IDictionary sectionContents) Unknown
[Lightweight Function]
Nancy.ViewEngines.Razor.dll!Nancy.ViewEngines.Razor.RazorViewEngine.RenderView.AnonymousMethod__26(System.IO.Stream stream) Unknown
Nancy.Hosting.Self.dll!Nancy.Hosting.Self.NancyHost.OutputWithDefaultTransferEncoding(Nancy.Response nancyResponse, System.Net.HttpListenerResponse response) Unknown
Nancy.Hosting.Self.dll!Nancy.Hosting.Self.NancyHost.ConvertNancyResponseToResponse(Nancy.Response nancyResponse, System.Net.HttpListenerResponse response) Unknown
Nancy.Hosting.Self.dll!Nancy.Hosting.Self.NancyHost.Process(System.Net.HttpListenerContext ctx) Unknown
Nancy.Hosting.Self.dll!Nancy.Hosting.Self.NancyHost.GotCallback(System.IAsyncResult ar) Unknown
System.dll!System.Net.LazyAsyncResult.Complete(System.IntPtr userToken) Unknown
System.dll!System.Net.LazyAsyncResult.ProtectedInvokeCallback(object result, System.IntPtr userToken) Unknown
System.dll!System.Net.ListenerAsyncResult.IOCompleted(System.Net.ListenerAsyncResult asyncResult, uint errorCode, uint numBytes) Unknown
System.dll!System.Net.ListenerAsyncResult.WaitCallback(uint errorCode, uint numBytes, System.Threading.NativeOverlapped* nativeOverlapped) Unknown
mscorlib.dll!System.Threading._IOCompletionCallback.PerformIOCompletionCallback(uint errorCode, uint numBytes, System.Threading.NativeOverlapped* pOVERLAP) Unknown
UPDATE:
That last stack trace seems to imply a problem with AspNet.Web.Optimization, perhaps related to this question:
Can't get System.Web.Optimization to run with Nancy Self Hosting

I would strip everything out of the view accept for a span tag.
<span>Hello</span>
Also I would strip everything out of the bootstrapper except the lines
needed for razor.
If this works then you know something else is tripping it up.

Related

Stackoverflow error comes in Microsoft.Extensions.Hosting class

I had Azure function which was written using .NET Core 3.1 and suddenly stopped working and showing StackOverflow exception in below code at TryAddEnumerables
Here is my stack trace
My startup class
builder.Services
.AddSingleton<IConfiguration>(config)
.AddSingleton(serviceProvider => serviceProvider)
.AddLogging()
.AddSingleton<IManager, CManager>()
.AddSingleton<IRegexManager, RegexManager>()
Removing below line solves the StackOverflow error but not sure on side affects of it
AddSingleton(serviceProvider => serviceProvider)
Trace
System.Private.CoreLib.dll!Interop.Advapi32.EventWriteTransfer_PInvoke(long registrationHandle, System.Diagnostics.Tracing.EventDescriptor eventDescriptor, System.Guid* activityId, System.Guid* relatedActivityId, int userDataCount, System.Diagnostics.Tracing.EventProvider.EventData* userData) Unknown
System.StackOverflowException
HResult=0x800703E9
Source=<Cannot evaluate the exception source>
StackTrace:
<Cannot evaluate the exception stack trace
System.Private.CoreLib.dll!Interop.Advapi32.EventWriteTransfer(long registrationHandle, System.Diagnostics.Tracing.EventDescriptor eventDescriptor, System.Guid* activityId, System.Guid* relatedActivityId, int userDataCount, System.Diagnostics.Tracing.EventProvider.EventData* userData) Unknown
System.Private.CoreLib.dll!System.Diagnostics.Tracing.EtwEventProvider.System.Diagnostics.Tracing.IEventProvider.EventWriteTransfer(long registrationHandle, System.Diagnostics.Tracing.EventDescriptor eventDescriptor, System.IntPtr eventHandle, System.Guid* activityId, System.Guid* relatedActivityId, int userDataCount, System.Diagnostics.Tracing.EventProvider.EventData* userData) Unknown
System.Private.CoreLib.dll!System.Diagnostics.Tracing.EventProvider.WriteEvent(ref System.Diagnostics.Tracing.EventDescriptor eventDescriptor, System.IntPtr eventHandle, System.Guid* activityID, System.Guid* childActivityID, int dataCount, System.IntPtr data) Unknown
System.Private.CoreLib.dll!System.Diagnostics.Tracing.EventSource.WriteEventWithRelatedActivityIdCore(int eventId, System.Guid* relatedActivityId, int eventDataCount, System.Diagnostics.Tracing.EventSource.EventData* data) Unknown
System.Private.CoreLib.dll!System.Threading.Tasks.TplEventSource.TraceOperationBegin(int TaskID, string OperationName, long RelatedContext) Unknown
System.Private.CoreLib.dll!System.Threading.Tasks.AsyncCausalityTracer.TraceOperationCreation(System.Threading.Tasks.Task task, string operationName) Unknown
System.Private.CoreLib.dll!System.Threading.Tasks.Task.ScheduleAndStart(bool needsProtection) Unknown

C# SOAP Middleware MessageEncoder.WriteMessage

I try to run this tutorial: custom-asp-net-core-middleware-example
But the reponse message at the client say´s:
S
ystem.ServiceModel.ProtocolException: There is a problem with the XML that was received from the network. See inner exception for more details.
---> System.Xml.XmlException: Name cannot begin with the '/' character, hexadecimal value 0x2F. Line 1, position 74.
at System.Xml.XmlExceptionHelper.ThrowXmlException(XmlDictionaryReader reader, XmlException exception)
at System.Xml.XmlUTF8TextReader.VerifyNCName(String s)
at System.Xml.XmlUTF8TextReader.ReadQualifiedName(PrefixHandle prefix, StringHandle localName)
at System.Xml.XmlUTF8TextReader.ReadStartElement()
at System.Xml.XmlUTF8TextReader.Read()
at System.ServiceModel.Channels.Message.ReadStartBody(XmlDictionaryReader reader, EnvelopeVersion envelopeVersion, Boolean& isFault, Boolean& isEmpty)
at System.ServiceModel.Channels.ReceivedMessage.ReadStartBody(XmlDictionaryReader reader)
at System.ServiceModel.Channels.BufferedMessage..ctor(IBufferedMessageData messageData, RecycledMessageState recycledMessageState, Boolean[] understoodHeaders, Boolean understoodHeadersModified)
at System.ServiceModel.Channels.BufferedMessage..ctor(IBufferedMessageData messageData, RecycledMessageState recycledMessageState)
at System.ServiceModel.Channels.TextMessageEncoderFactory.TextMessageEncoder.ReadMessage(ArraySegment`1 buffer, BufferManager bufferManager, String contentType)
at System.ServiceModel.Channels.MessageEncoder.ReadMessageAsync(Stream stream, BufferManager bufferManager, Int32 maxBufferSize, String contentType, CancellationToken cancellationToken)
at System.ServiceModel.Channels.HttpResponseMessageHelper.ReadChunkedBufferedMessageAsync(Task`1 inputStreamTask, TimeoutHelper timeoutHelper)
--- End of inner exception stack trace ---
at System.Runtime.AsyncResult.End[TAsyncResult](IAsyncResult result)
at System.ServiceModel.Channels.ServiceChannel.SendAsyncResult.End(SendAsyncResult result)
at System.ServiceModel.Channels.ServiceChannel.EndCall(String action, Object[] outs, IAsyncResult result)
at System.ServiceModel.Channels.ServiceChannelProxy.TaskCreator.<>c__DisplayClass1_0.<CreateGenericTask>b__0(IAsyncResult asyncResult)
I´ve also encounterd a problem with the request-message so I´ve written my own RequestMessage but I´m not sure whether I should write my own ResponseMessage, because I do not know how it should be.
Also I´ve changed the OperationDescription to fit the tutorials code, may there be the problem?
public OperationDescription(ContractDescription contract, MethodInfo operationMethod, OperationContractAttribute contractAttribute)
{
Contract = contract;
SoapAction = contractAttribute.Name ?? operationMethod.Name;
Name = contractAttribute.Action ?? $"{contract.Namespace.TrimEnd('/')}/{contract.Name}/{Name}".Trim('/');
IsOneWay = contractAttribute.IsOneWay;
ReplyAction = contractAttribute.ReplyAction;
DispatchMethod = operationMethod;
}

GraphQL json parser and AllowSynchronousIO

I'm starting to implement GraphQA in .NET with https://github.com/graphql-dotnet/server, I wrote a very simple sample application and while running Graphiql I got the following error:
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
System.InvalidOperationException: Synchronous operations are disallowed. Call ReadAsync or set AllowSynchronousIO to true instead.
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpRequestStream.Read(Byte[] buffer, Int32 offset, Int32 count)
at System.IO.StreamReader.ReadBuffer(Span`1 userBuffer, Boolean& readToUserBuffer)
at System.IO.StreamReader.ReadSpan(Span`1 buffer)
at System.IO.StreamReader.Read(Char[] buffer, Int32 index, Int32 count)
at Newtonsoft.Json.JsonTextReader.ReadData(Boolean append, Int32 charsRequired)
at Newtonsoft.Json.JsonTextReader.ParseValue()
at Newtonsoft.Json.JsonReader.ReadForType(JsonContract contract, Boolean hasConverter)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonSerializer.Deserialize[T](JsonReader reader)
at GraphQL.Server.Transports.AspNetCore.GraphQLHttpMiddleware`1.Deserialize[T](Stream s)
at GraphQL.Server.Transports.AspNetCore.GraphQLHttpMiddleware`1.InvokeAsync(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.InvokeCore(HttpContext context, ICorsPolicyProvider corsPolicyProvider)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
I found a workaround here https://github.com/graphql-dotnet/graphql-dotnet/issues/1116 which states that the configuration for IIS/Krestel needs to allow Synchronous IO using the following:
services.Configure<IISServerOptions>(options =>
{
options.AllowSynchronousIO = true;
});
I see that https://www.nuget.org/packages/GraphQL.Server.Transports.AspNetCore.NewtonsoftJson is still in alpha, so I'm guessing I have to use the build in JSON parser of .NET Core 3.1.
What are the implications of setting AllowSynchronousIO would it make the calls the server can handle slower?

System.ComponentModel.Win32Exception occurs with Parameter is incorrect message while accessing control through automation

I am trying to access a wpf control using AutomationElement but sometimes it throws and exception.
Below is the code:
if (automationElement.TryGetCurrentPattern(ValuePattern.Pattern, out pattern))
{
ValuePattern valuePattern = pattern as ValuePattern;
valuePattern.SetValue(valueToBeSet);
}
I am doing till here, this triggers some methods calls in MS.Win32.UnsafeNativeMethods which then gives the exception.
Stack trace from event log:
Exception Messages:
Win32Exception : The parameter is incorrect
Type : System.ComponentModel.Win32Exception, System, Version=4.0.0.0, Culture=neutral
Message : The parameter is incorrect
Source : WindowsBase
NativeErrorCode: 87
ErrorCode : -2147467259
TargetSite : Int32 GetWindowText(System.Runtime.InteropServices.HandleRef, System.Text.StringBuilder, Int32)
Stack Trace : at MS.Win32.UnsafeNativeMethods.GetWindowText(HandleRef hWnd, StringBuilder lpString, Int32 nMaxCount)
at System.Windows.Automation.Peers.WindowAutomationPeer.GetNameCore()
at System.Windows.Automation.Peers.AutomationPeer.UpdateSubtree()
at System.Windows.ContextLayoutManager.fireAutomationEvents()
at System.Windows.ContextLayoutManager.UpdateLayout()
at System.Windows.ContextLayoutManager.UpdateLayoutCallback(Object arg)
at System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks()
at System.Windows.Media.MediaContext.RenderMessageHandlerCore(Object resizedCompositionTarget)
at System.Windows.Media.MediaContext.AnimatedRenderMessageHandler(Object resizedCompositionTarget)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
The WPF control is standard WPF control(No customization). I am not able to cause of this error. I believe it is the window handle which is incorrect(param for GetWindowText) but have no idea how to check this? In case it is something else please do tell.

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