OData v4 DefaultODataBatchHandler NotImplementedException - odata

In my web service I've setup for batch requests. I wrapped the DefaultODataBatchHandler class just to add break points. It is processing the requests successfully and the CreateResponseMessageAsync method is creating a 200 OK response. But the client is receiving the following:
{
"Message": "An error has occurred.",
"ExceptionMessage": "The method or operation is not implemented.",
"ExceptionType": "System.NotImplementedException",
"StackTrace": " at System.Web.HttpContextBase.get_Response()\r\n at System.Web.UI.Util.GetUrlWithApplicationPath(HttpContextBase context, String url)\r\n at System.Web.Routing.RouteCollection.NormalizeVirtualPath(RequestContext requestContext, String virtualPath)\r\n at System.Web.Routing.RouteCollection.GetVirtualPath(RequestContext requestContext, String name, RouteValueDictionary values)\r\n at System.Web.Http.WebHost.Routing.HostedHttpRouteCollection.GetVirtualPath(HttpRequestMessage request, String name, IDictionary`2 values)\r\n at System.Web.Http.Routing.UrlHelper.GetVirtualPath(HttpRequestMessage request, String routeName, IDictionary`2 routeValues)\r\n at System.Web.Http.Routing.UrlHelper.Route(String routeName, IDictionary`2 routeValues)\r\n at System.Web.Http.Routing.UrlHelper.Link(String routeName, IDictionary`2 routeValues)\r\n at System.Web.OData.Extensions.UrlHelperExtensions.CreateODataLink(UrlHelper urlHelper, String routeName, IODataPathHandler pathHandler, IList`1 segments)\r\n at System.Web.OData.Extensions.UrlHelperExtensions.CreateODataLink(UrlHelper urlHelper, IList`1 segments)\r\n at System.Web.OData.Formatter.ODataMediaTypeFormatter.GetDefaultBaseAddress(HttpRequestMessage request)\r\n at System.Web.OData.Formatter.ODataMediaTypeFormatter.GetBaseAddressInternal(HttpRequestMessage request)\r\n at System.Web.OData.Formatter.ODataMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content, HttpContentHeaders contentHeaders)\r\n at System.Web.OData.Formatter.ODataMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Net.Http.HttpContent.<CopyToAsyncCore>d__44.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.OData.Batch.ODataBatchResponseItem.<WriteMessageAsync>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.OData.Batch.ODataBatchContent.<SerializeToStreamAsync>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Net.Http.HttpContent.<LoadIntoBufferAsyncCore>d__49.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Owin.HttpMessageHandlerAdapter.<BufferResponseContentAsync>d__13.MoveNext()"
}
I have no idea why or where this is coming from.
ODataConfig.cs
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var builder = new ODataConventionModelBuilder();
var tags = builder.EntitySet<EventTag>("EventTags");
tags.HasOptionalBinding(x => x.Parent, tags);
var events = builder.EntitySet<Event>("Events");
events.HasManyBinding(x => x.Tags, tags);
var batchHandler = new DefaultODataBatchHandler(GlobalConfiguration.DefaultServer);
config.MapODataServiceRoute("odata", "odata", builder.GetEdmModel(), batchHandler);
}
}

I resolved this by making sure I called into Register with a new instance of HttpConfiguration, rather than re-using one from before (which I had wired up Autofac on). I guess you could get the same problems if you tried to wire this up using GlobalConfiguration.Configuration.
Trick is to set up WebApi on a new HttpConfiguration instance.

Related

Acumatica throwing a 500 Server Exception when refreshing the OAuth 2 Access token

I'm receiving a 500 Server Exception when the Refresh Token for OAuth 2 takes place. How do I go about resolving this exception? Any assistance will be greatly appreciated.
The full exception message is:
Unhandled exception accessing: /identity/connect/token
System.NullReferenceException: Object reference not set to an instance of an object.
Stack Trace:
at IdentityServer3.Core.Validation.TokenRequestValidator.<ValidateRefreshTokenRequestAsync>d__30.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer3.Core.Validation.TokenRequestValidator.<RunValidationAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer3.Core.Validation.TokenRequestValidator.<ValidateRequestAsync>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer3.Core.Endpoints.TokenEndpointController.<ProcessAsync>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer3.Core.Endpoints.TokenEndpointController.<Post>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Threading.Tasks.System.Web.Http910911.TaskHelpersExtensions.<CastToObject>d__3`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
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.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Filters.ActionFilterAttribute.<ExecuteActionFilterAsyncCore>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
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.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Filters.AuthorizationFilterAttribute.<ExecuteAuthorizationFilterAsyncCore>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()
Some more detail:
We're making use of a web-based integration service called Integromat. The service fully supports the OAuth 1 & 2 protocols.
We've configured the client application on the Connected Applications screen using the Authorization Code flow, and we're able to get the initial authorization working. i.e. we're receiving the access token and are able to make subsequent API calls using the Contract-Based REST API.
The issue comes in when the initial access token expires.
We have already reached out to Integromat's support team and they are also not able to see anything obvious wrong with the request being sent through on the refresh token phase.
Note we have reviewed & compared the below with this help article.
Below is an overview of the OAuth setup in Integromat:
{
"authorize": {
"qs": {
"scope": "{{join(oauth.scope, ' ')}}", -- this basically equates to api%20offline_access
"client_id": "{{ifempty(parameters.clientId, common.clientId)}}",
"redirect_uri": "{{oauth.redirectUri}}",
"response_type": "code"
},
"url": "https://our-instance/identity/connect/authorize",
"response": {
"temp": {
"code": "{{query.code}}"
}
}
},
"token": {
"url": "https://our-instance/identity/connect/token",
"method": "POST",
"body": {
"code": "{{temp.code}}",
"client_id": "{{ifempty(parameters.clientId, common.clientId)}}",
"grant_type": "authorization_code",
"redirect_uri": "{{oauth.redirectUri}}",
"client_secret": "{{ifempty(parameters.clientSecret, common.clientSecret)}}"
},
"type": "urlencoded",
"response": {
"data": {
"expires": "{{addSeconds(now, body.expires_in)}}",
"accessToken": "{{body.access_token}}",
"refreshToken": "{{body.refresh_token}}"
},
"expires": "{{addSeconds(now, body.expires_in)}}"
},
"log": {
"sanitize": ["request.body.code", "request.body.client_secret", "response.body.access_token", "response.body.refresh_token"]
}
},
"refresh": {
"condition": "{{data.expires < addMinutes(now, 60)}}",
"url": "https://our-instance/identity/connect/token",
"headers": {
"Authorization": "Bearer {{connection.accessToken}}"
},
"method": "POST",
"body": {
"client_id": "{{ifempty(parameters.clientId, common.clientId)}}",
"grant_type": "refresh_token",
"client_secret": "{{ifempty(parameters.clientSecret, common.clientSecret)}}",
"refresh_token": "{{data.refreshToken}}"
},
"type": "urlencoded",
"response": {
"data": {
"expires": "{{addSeconds(now, body.expires_in)}}",
"accessToken": "{{body.access_token}}"
},
"expires": "{{addSeconds(now, body.expires_in)}}"
},
"log": {
"sanitize": ["request.body.code", "request.body.client_secret", "response.body.access_token", "response.body.refresh_token"]
}
},
"info": {
"url": "https://our-instance/entity/SIH/18.200.001/Currency/",
"headers": {
"Authorization": "Bearer {{connection.accessToken}}"
},
"method": "GET",
"response": {
"uid": "{{body.id}}",
"metadata": {
"type": "text",
"value": "{{body.user}}"
}
},
"log": {
"sanitize": ["request.headers.authorization"]
}
},
"invalidate": {
"url": "https://our-instance/entity/auth/logout",
"headers": {
"authorization": "Bearer {{connection.accessToken}}"
},
"log": {
"sanitize": ["request.headers.authorization"]
}
}
}
Some additional Request Profile logs on the /identity/connect/token can be seen below:
The FirstChanceException is as follows:
You are not currently logged in.
Stack Trace:
at PX.Data.PXFirstChanceExceptionLogger.a(Object A_0, FirstChanceExceptionEventArgs A_1)
at PX.Data.PXDatabaseProviderBase.c()
at PX.Data.PXDatabaseProviderBase.getCompanyID(String tableName, companySetting& setting)
at PX.Data.PXDatabaseProviderBase.GetSlot[ObjectType](String key, PrefetchDelegate`1 prefetchDelegate, Type[] tables)
at PX.Data.PXDatabase.GetSlot[ObjectType](String key, Type[] tables)
at PX.Data.PXGraph.b(Type A_0)
at PX.Data.PXGraph.CreateInstance(Type graphType, String prefix)
at PX.Data.PXGraph.CreateInstance(Type graphType)
at PX.Data.PXGraph.CreateInstance[Graph]()
at PX.Owin.IdentityServerIntegration.TokenStoreBase`2.GetImpl(String key)
at PX.Owin.IdentityServerIntegration.TokenStoreBase`2.GetAsync(String key)
at IdentityServer3.Core.Validation.TokenRequestValidator.<ValidateRefreshTokenRequestAsync>d__30.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine& stateMachine)
at IdentityServer3.Core.Validation.TokenRequestValidator.ValidateRefreshTokenRequestAsync(NameValueCollection parameters)
at IdentityServer3.Core.Validation.TokenRequestValidator.<RunValidationAsync>d__5.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine& stateMachine)
at IdentityServer3.Core.Validation.TokenRequestValidator.RunValidationAsync(Func`2 validationFunc, NameValueCollection parameters)
at IdentityServer3.Core.Validation.TokenRequestValidator.<ValidateRequestAsync>d__0.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine& stateMachine)
at IdentityServer3.Core.Validation.TokenRequestValidator.ValidateRequestAsync(NameValueCollection parameters, Client client)
at IdentityServer3.Core.Endpoints.TokenEndpointController.<ProcessAsync>d__7.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine& stateMachine)
at IdentityServer3.Core.Endpoints.TokenEndpointController.ProcessAsync(NameValueCollection parameters)
at IdentityServer3.Core.Endpoints.TokenEndpointController.<Post>d__0.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine& stateMachine)
at IdentityServer3.Core.Endpoints.TokenEndpointController.Post()
at lambda_method(Closure , Object , Object[] )
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass12.<GetExecutor>b__8(Object instance, Object[] methodParameters)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()
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.Controllers.ActionFilterResult.<ExecuteAsync>b__0(ActionInvoker innerInvoker)
at System.Web.Http.Controllers.ActionFilterResult.<>c__DisplayClass10`1.<InvokeActionWithActionFilters>b__f()
at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine& stateMachine)
at System.Web.Http.Filters.ActionFilterAttribute.CallOnActionExecutedAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func`1 continuation)
at System.Web.Http.Filters.ActionFilterAttribute.<ExecuteActionFilterAsyncCore>d__0.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine& stateMachine)
at System.Web.Http.Filters.ActionFilterAttribute.ExecuteActionFilterAsyncCore(HttpActionContext actionContext, CancellationToken cancellationToken, Func`1 continuation)
at System.Web.Http.Filters.ActionFilterAttribute.System.Web.Http.Filters.IActionFilter.ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func`1 continuation)
at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine& stateMachine)
at System.Web.Http.Controllers.ActionFilterResult.ExecuteAsync(CancellationToken cancellationToken)
at System.Web.Http.Filters.AuthorizationFilterAttribute.<ExecuteAuthorizationFilterAsyncCore>d__2.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine& stateMachine)
at System.Web.Http.Filters.AuthorizationFilterAttribute.ExecuteAuthorizationFilterAsyncCore(HttpActionContext actionContext, CancellationToken cancellationToken, Func`1 continuation)
at System.Web.Http.Filters.AuthorizationFilterAttribute.System.Web.Http.Filters.IAuthorizationFilter.ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func`1 continuation)
at System.Web.Http.Controllers.AuthorizationFilterResult.ExecuteAsync(CancellationToken cancellationToken)
at System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)
at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()
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.Owin.PassiveAuthenticationMessageHandler.<SendAsync>d__0.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine& stateMachine)
at System.Web.Http.Owin.PassiveAuthenticationMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.DelegatingHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at Autofac.Integration.WebApi.Owin.DependencyScopeHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.DelegatingHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Web.Http.HttpServer.<SendAsync>d__0.MoveNext()
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.Owin.HttpMessageHandlerAdapter.<InvokeCore>d__0.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine)
at System.Web.Http.Owin.HttpMessageHandlerAdapter.InvokeCore(IOwinContext context, IOwinRequest owinRequest, IOwinResponse owinResponse)
at Owin.SignOutMessageCookieExtension.<<ConfigureSignOutMessageCookie>b__0>d__5.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine)
at Owin.SignOutMessageCookieExtension.<ConfigureSignOutMessageCookie>b__0(IOwinContext context, Func`1 next)
at Owin.UseCookieAuthenticationExtension.<>c__DisplayClass9.<<ConfigureCookieAuthentication>b__6>d__10.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine)
at Owin.UseCookieAuthenticationExtension.<>c__DisplayClass9.<ConfigureCookieAuthentication>b__6(IOwinContext ctx, Func`1 next)
at Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware`1.<Invoke>d__0.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine)
at Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware`1.Invoke(IOwinContext context)
at Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware`1.<Invoke>d__0.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine)
at Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware`1.Invoke(IOwinContext context)
at Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware`1.<Invoke>d__0.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine)
at Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware`1.Invoke(IOwinContext context)
at Microsoft.Owin.Cors.CorsMiddleware.<Invoke>d__0.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine)
at Microsoft.Owin.Cors.CorsMiddleware.Invoke(IDictionary`2 environment)
at Owin.OwinExtensions.<>c__DisplayClass2.<<UseAutofacMiddleware>b__0>d__7.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine)
at Owin.OwinExtensions.<>c__DisplayClass2.<UseAutofacMiddleware>b__0(IOwinContext context, Func`1 next)
at Owin.ConfigureRenderLoggedOutPageExtension.<<ConfigureRenderLoggedOutPage>b__0>d__2.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine)
at Owin.ConfigureRenderLoggedOutPageExtension.<ConfigureRenderLoggedOutPage>b__0(IOwinContext ctx, Func`1 next)
at Owin.ConfigureRequestBodyBufferExtension.<<ConfigureRequestBodyBuffer>b__0>d__2.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine)
at Owin.ConfigureRequestBodyBufferExtension.<ConfigureRequestBodyBuffer>b__0(IOwinContext context, Func`1 next)
at Owin.ConfigureIdentityServerIssuerExtension.<>c__DisplayClass5.<<ConfigureIdentityServerIssuer>b__1>d__7.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine)
at Owin.ConfigureIdentityServerIssuerExtension.<>c__DisplayClass5.<ConfigureIdentityServerIssuer>b__1(IOwinContext ctx, Func`1 next)
at Owin.ConfigureIdentityServerBaseUrlExtension.<>c__DisplayClass1.<<ConfigureIdentityServerBaseUrl>b__0>d__3.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine)
at Owin.ConfigureIdentityServerBaseUrlExtension.<>c__DisplayClass1.<ConfigureIdentityServerBaseUrl>b__0(IOwinContext ctx, Func`1 next)
at Owin.ConfigureRequestIdExtension.<<ConfigureRequestId>b__0>d__2.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine)
at Owin.ConfigureRequestIdExtension.<ConfigureRequestId>b__0(IOwinContext ctx, Func`1 next)
at Microsoft.Owin.StaticFiles.StaticFileMiddleware.Invoke(IDictionary`2 environment)
at Microsoft.Owin.StaticFiles.DefaultFilesMiddleware.Invoke(IDictionary`2 environment)
at Microsoft.Owin.StaticFiles.StaticFileMiddleware.Invoke(IDictionary`2 environment)
at Microsoft.Owin.StaticFiles.DefaultFilesMiddleware.Invoke(IDictionary`2 environment)
at IdentityServer3.Core.Configuration.Hosting.RequireSslMiddleware.<Invoke>d__0.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine)
at IdentityServer3.Core.Configuration.Hosting.RequireSslMiddleware.Invoke(IDictionary`2 env)
at Microsoft.Owin.Mapping.MapMiddleware.<Invoke>d__0.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine)
at Microsoft.Owin.Mapping.MapMiddleware.Invoke(IDictionary`2 environment)
at PX.Owin.Startup.<>c.<<ConfigurationImpl>b__10_0>d.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine)
at PX.Owin.Startup.<>c.<ConfigurationImpl>b__10_0(IOwinContext ctx, Func`1 n)
at Owin.AutofacAppBuilderExtensions.<>c__DisplayClass10_0.<<RegisterAutofacLifetimeScopeInjector>b__0>d.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine)
at Owin.AutofacAppBuilderExtensions.<>c__DisplayClass10_0.<RegisterAutofacLifetimeScopeInjector>b__0(IOwinContext context, Func`1 next)
at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContextStage.<RunApp>d__5.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine)
at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContextStage.RunApp(Func`2 entryPoint, IDictionary`2 environment, TaskCompletionSource`1 tcs, StageAsyncResult result)
at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContextStage.BeginEvent(Object sender, EventArgs e, AsyncCallback cb, Object extradata)
at System.Web.HttpApplication.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)
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.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)
This might be due to the fact that you are trying to use the refresh token multiple time.
Each refresh token can only be used a single time.
Once a refresh token is used it provides you with a new token and a new refresh token. The refresh token that you have just used becomes obsolete and you need to use the new one in order to get a new token/refresh token combo.

System.IO.IOException: IDX10804: Unable to retrieve document from: 'http://localhost:51156/.well-known/openid-configuration&#x27

I have generated a token using JwtSecurityToken, however, when I have added it to request header in postman to call an action in my api, I encounter this exception:
System.IO.IOException: IDX10804: Unable to retrieve document from: 'http://localhost:51156/.well-known/openid-configuration'. ---> System.Net.Http.HttpRequestException: Response status code does not indicate success: 404 (Not Found).
at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.<GetDocumentAsync>d__8.MoveNext()
--- End of inner exception stack trace ---
at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.<GetDocumentAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult()
at Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfigurationRetriever.<GetAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult()
at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.<GetConfigurationAsync>d__24.MoveNext()
This is how I generate tokens: (for the sake of simplicity, I have hard-coded some values temporarily instead of reading from appsettings.json)
[AllowAnonymous]
[HttpPost]
[Route("")]
public IActionResult RequestToken([FromBody] TokenRequest request)
{
if (request.Username == "Jon" && request.Password == "123456")
{
var claims = new[]
{
new Claim(ClaimTypes.Name, request.Username)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_securityConfig.Key));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: "http://localhost:51156/",
audience: "http://localhost:51156/",
claims: claims,
expires: DateTime.Now.AddDays(3),
signingCredentials: creds);
return Ok(new
{
token = new JwtSecurityTokenHandler().WriteToken(token)
});
}
return BadRequest("Could not verify username and password");
}
And this is how my ConfigureService method is:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = "http://localhost:51156/";
options.Audience = "http://localhost:51156/";
options.RequireHttpsMetadata = false;
});
}
Any advise or guidance would be greatly appreciated.

How to get Swashbuckle working on sitefinity 10.x

I had installed Swashbuckle on Sitefinity 7.x and it was working just fine, after update my Sitefinity project to 10.x it stopped working (getting 500 error). I have tried different version of Swashbuckle with the same setup without success, I have also tried some different Swashbuckle configuration without much luck.
This is the setup code I have in the Sitefinity project's Global.asax (which used to work)
protected void Application_Start(object sender, EventArgs e)
{
Bootstrapper.Initialized += Bootstrapper_Initialized;
}
private void Bootstrapper_Initialized(object sender, ExecutedEventArgs args)
{
RouteTable.Routes.Ignore("ipad");
if (args.CommandName == "RegisterRoutes")
{
RegisterRoutes(RouteTable.Routes);
CustomPageRouteHandler.RegisterType();
GlobalConfiguration.Configuration.Filters.Add(new LoggingFilterAttribute());
GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpActionInvoker), new ControllerActionInvoker());
GlobalConfiguration.Configuration.Filters.Add(new ApiExceptionFilterAttribute());
JsonDefaultSerializer.ConfigureApi(GlobalConfiguration.Configuration);
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.SingleApiVersion("v1", "xxx.Web");
c.DocumentFilter<SwaggerCustomControllersFilter>();
c.IgnoreObsoleteActions();
c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
})
.EnableSwaggerUi(c =>
{
c.DisableValidator();
});
GlobalConfiguration.Configuration.EnsureInitialized();
}
}
The following is the error message I am getting:
{
"Message": "An error has occurred.",
"ExceptionMessage": "Object reference not set to an instance of an object.",
"ExceptionType": "System.NullReferenceException",
"StackTrace": " at System.Collections.Generic.DictionaryExtensions.TryGetValue[T](IDictionary2 collection, String key, T& value)
at System.Web.Http.Description.ApiExplorer.ExploreRouteControllers(IDictionary2 controllerMappings, IHttpRoute route)
at System.Web.Http.Description.ApiExplorer.InitializeApiDescriptions()
at System.Lazy1.CreateValue()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Lazy1.get_Value()
at Swashbuckle.Swagger.SwaggerGenerator.GetSwagger(String rootUrl, String apiVersion)
at Swashbuckle.Application.SwaggerDocsHandler.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.Cors.CorsMessageHandler.d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.HttpServer.d__0.MoveNext()"
}
here are some of the packages versions:
Swashbuckle 5.6.0
Swashbuckle.Core 5.6.0
System.Net.Http 4.3.3
WebActivatorEx 2.2.0

Error creating ASP web page with single sign on over AAD

I'm struggling with creating an ASP web page with SSO like in this tutorial https://learn.microsoft.com/en-us/aspnet/identity/overview/getting-started/developing-aspnet-apps-with-windows-azure-active-directory but first I got redirected to localhost after deploying the aplication, so I searched and found the solution in ASP.Net redirecting to local host after authentication. But now when I autenticate on the web page I've created I get the next error
[ArgumentException: Format of the initialization string does not conform to specification starting at index 152.]
System.Data.Common.DbConnectionOptions.GetKeyValuePair(String connectionString, Int32 currentPosition, StringBuilder buffer, Boolean useOdbcRules, String& keyname, String& keyvalue) +5778570
System.Data.Common.DbConnectionOptions.ParseInternal(Hashtable parsetable, String connectionString, Boolean buildChain, Hashtable synonyms, Boolean firstKey) +124
System.Data.Common.DbConnectionOptions..ctor(String connectionString, Hashtable synonyms, Boolean useOdbcRules) +95
System.Data.SqlClient.SqlConnectionString..ctor(String connectionString) +59
System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous) +27
System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions) +167
System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key) +61
System.Data.SqlClient.SqlConnection.set_ConnectionString(String value) +87
System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.<SetConnectionString>b__18(DbConnection t, DbConnectionPropertyInterceptionContext`1 c) +12
System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch(TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed) +72
System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.SetConnectionString(DbConnection connection, DbConnectionPropertyInterceptionContext`1 interceptionContext) +360
System.Data.Entity.Internal.LazyInternalConnection.InitializeFromConnectionStringSetting(ConnectionStringSettings appConfigConnection) +269
System.Data.Entity.Internal.LazyInternalConnection.TryInitializeFromAppConfig(String name, AppConfig config) +32
System.Data.Entity.Internal.LazyInternalConnection.Initialize() +127
System.Data.Entity.Internal.LazyInternalConnection.get_ProviderName() +13
System.Data.Entity.Internal.LazyInternalContext.get_ProviderName() +11
System.Data.Entity.Internal.DefaultModelCacheKeyFactory.Create(DbContext context) +92
System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +515
System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +18
System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +53
System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext() +15
System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider() +38
System.Linq.Queryable.FirstOrDefault(IQueryable`1 source, Expression`1 predicate) +83
pruebamvc.Models.ADALTokenCache..ctor(String signedInUserId) +380
pruebamvc.Startup.<ConfigureAuth>b__7_0(AuthorizationCodeReceivedNotification context) +111
Microsoft.Owin.Security.OpenIdConnect.<AuthenticateCoreAsync>d__1a.MoveNext() +4931
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +26
Microsoft.Owin.Security.OpenIdConnect.<AuthenticateCoreAsync>d__1a.MoveNext() +6453
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
Microsoft.Owin.Security.Infrastructure.<BaseInitializeAsync>d__0.MoveNext() +571
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
Microsoft.Owin.Security.Infrastructure.<Invoke>d__0.MoveNext() +255
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.<RunApp>d__5.MoveNext() +182
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
Microsoft.Owin.Security.Infrastructure.<Invoke>d__0.MoveNext() +638
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.<RunApp>d__5.MoveNext() +182
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.<DoFinalWork>d__2.MoveNext() +180
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult ar) +69
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar) +64
System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +380
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
I've searched if anybody else has got the same error, but not success. I have tried to update nuget packages because it looks like a parsing error with the tokem, but in Startup.Auth.cs sais that authenticationcontext has AcquireTokenByAuthorizationCode deprecated so I tried to replace old code
AuthorizationCodeReceived = (context) =>
{
var code = context.Code;
ClientCredential credential = new ClientCredential(clientId, appKey);
string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
AuthenticationContext authContext = new AuthenticationContext(Authority, new ADALTokenCache(signedInUserID));
AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);
return Task.FromResult(0);
}
with:
AuthorizationCodeReceived = async (context) =>
{
var code = context.Code;
ClientCredential credential = new ClientCredential(clientId, appKey);
string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
AuthenticationContext authContext = new AuthenticationContext(Authority, new ADALTokenCache(signedInUserID));
AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(
code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);
return ;
}
But still etting errors. Do you have any idea?
but first I got redirected to localhost after deploying the apllication
You could change the redirect url both in web.config and azure ad application , please follow below steps :
After deploy , you will get the published app url :https://webapplicationname.azurewebsites.net/ , cope the url and modify the web config :
<add key="ida:PostLogoutRedirectUri" value="https://webapplicationname.azurewebsites.net/" />
In azure portal ,click Azure AD blade, click "App registrations" button , find the app you registered . You could find the app by app id(client id) , that could be find in web config:
<add key="ida:ClientId" value="ae7afda3-b24b-42a7-bb14-8d7a08227f66" />
select the app , click "Reply URLs" button , add the published app url(this demo i used webapplication420170330110754 as my app name ,change that to your own app name ) ,click save button:
Now you need to re-publish the app to make the new web.config available .
Edit :
For this error ,please firstly confirm whether you have set the correct connect string . You could find the connect string of azure sql :
Click the connect string you will get that :

ASP.Net MVC controller route when large records

In my application I have a page that displays a list of records and with every record there is a link to click for more details of that record. It goes to the other controller.
Let me tell a sequence. From 'ToDoListSelect' controller it goes to 'ToDoList' and on clicking the link from ToDoList it goes to 'Info' controller. Everything works fine on my development machine with same database as on the server.
Now, I put the package on server and there it works okay if the records on the page are less than 500 or so. If there are more records then from ToDoList it does not go to Info but throws exception and I see it's going to ToDoListSelect which is weird. I do not know where to start looking for the problem. Any suggestions? Any details needed just let me know.
Here are the routes in my application:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute( "Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
The error thrown is:
Server Error in '/' Application.
The operation is invalid because of the current state of the object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about this error, view and determine where the error originated in the code.
Exception Details: System.InvalidOperationException: Operation is not valid due to the current state of the object.
Source Error:
During execution of the current web request An unhandled exception was generated. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
[InvalidOperationException: Der Vorgang ist aufgrund des aktuellen Zustands des Objekts ungültig.]
System.Web.HttpRequest.FillInFormCollection() +11485999
System.Web.HttpRequest.get_Form() +157
Microsoft.Web.Infrastructure.DynamicValidationHelper.<>c__DisplayClass12.<ReplaceCollection>b__e() +63
Microsoft.Web.Infrastructure.DynamicValidationHelper.<>c__DisplayClass12.<ReplaceCollection>b__11() +20
Microsoft.Web.Infrastructure.DynamicValidationHelper.DeferredCountArrayList.get_Count() +20
System.Web.HttpRequest.ValidateNameValueCollection(NameValueCollection nvc, RequestValidationSource requestCollection) +34
System.Web.HttpRequest.get_Form() +212
System.Web.Mvc.FormValueProvider..ctor(ControllerContext controllerContext, IUnvalidatedRequestValues unvalidatedValues) +55
System.Web.Mvc.FormValueProviderFactory.GetValueProvider(ControllerContext controllerContext) +61
System.Web.Mvc.<>c__DisplayClassc.<GetValueProvider>b__7(ValueProviderFactory factory) +28
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +238
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +148
System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +472
System.Linq.Enumerable.ToList(IEnumerable`1 source) +80
System.Web.Mvc.ValueProviderFactoryCollection.GetValueProvider(ControllerContext controllerContext) +347
System.Web.Mvc.ControllerBase.get_ValueProvider() +46
System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +80
System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +153
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +691
System.Web.Mvc.Controller.ExecuteCore() +162
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +305
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +62
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +20
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +469
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +375
Figured it out! Thanks Mr. Google!
http://geekswithblogs.net/renso/archive/2012/01/19/operation-is-not-valid-due-to-the-current-state-of.aspx
Put the change in web.config and it works fine.

Resources