How to get Swashbuckle working on sitefinity 10.x - swagger

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

Related

IConfidentialClientApplication AcquireTokenForClient exception being thrown periodically

I built a NotificationService factory for checking 2 different mailboxes. Everything works fine but periodically I receive an error email. Below is the method throwing the exception and the exception message itself
private async Task<string> GetAccessToken()
{
try {
string token = string.Empty;
IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(_settings.AzureClientID)
.WithCertificate(_settings.Certificate)
.WithAuthority($"https://login.microsoftonline.com/{_settings.AzureTenantID}")
.WithRedirectUri("https://daemon")
.Build();
string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
var result = await app.AcquireTokenForClient(scopes).ExecuteAsync();
return result.AccessToken;
}
catch (Exception ex)
{
_logger.LogError($"{DateTime.Now.ToString()}: Exception within GetAccessToken\r\n{ex}", ex);
}
return string.Empty;
}
2/8/2023 9:28:19 AM: Exception within GetAccessToken
System.Net.Http.HttpRequestException: An error occurred while sending the request.
---> System.IO.IOException: Unable to read data from the transport connection: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond..
---> System.Net.Sockets.SocketException (10060): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
--- End of inner exception stack trace ---
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.GetResult(Int16 token)
at System.Net.Security.SslStream.ReadAsyncInternal[TIOAdapter](TIOAdapter adapter, Memory1 buffer) at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken) --- End of inner exception stack trace --- at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken) at System.Net.Http.AuthenticationHelper.SendWithNtAuthAsync(HttpRequestMessage request, Uri authUri, Boolean async, ICredentials credentials, Boolean isProxyAuth, HttpConnection connection, HttpConnectionPool connectionPool, CancellationToken cancellationToken) at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken) at System.Net.Http.AuthenticationHelper.SendWithAuthAsync(HttpRequestMessage request, Uri authUri, Boolean async, ICredentials credentials, Boolean preAuthenticate, Boolean isProxyAuth, Boolean doRequestAuth, HttpConnectionPool pool, CancellationToken cancellationToken) at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken) at System.Net.Http.HttpClient.SendAsyncCore(HttpRequestMessage request, HttpCompletionOption completionOption, Boolean async, Boolean emitTelemetryStartStop, CancellationToken cancellationToken) at Microsoft.Identity.Client.Http.HttpManager.ExecuteAsync(Uri endpoint, IDictionary2 headers, HttpContent body, HttpMethod method, ILoggerAdapter logger, CancellationToken cancellationToken)
at Microsoft.Identity.Client.Http.HttpManager.ExecuteWithRetryAsync(Uri endpoint, IDictionary2 headers, HttpContent body, HttpMethod method, ILoggerAdapter logger, Boolean doNotThrow, Boolean retry, CancellationToken cancellationToken) at Microsoft.Identity.Client.Http.HttpManager.SendPostAsync(Uri endpoint, IDictionary2 headers, HttpContent body, ILoggerAdapter logger, CancellationToken cancellationToken)
at Microsoft.Identity.Client.Http.HttpManager.SendPostAsync(Uri endpoint, IDictionary2 headers, IDictionary2 bodyParameters, ILoggerAdapter logger, CancellationToken cancellationToken)
at Microsoft.Identity.Client.OAuth2.OAuth2Client.ExecuteRequestAsync[T](Uri endPoint, HttpMethod method, RequestContext requestContext, Boolean expectErrorsOn200OK, Boolean addCommonHeaders, Func2 onBeforePostRequestData) at Microsoft.Identity.Client.OAuth2.OAuth2Client.GetTokenAsync(Uri endPoint, RequestContext requestContext, Boolean addCommonHeaders, Func2 onBeforePostRequestHandler)
at Microsoft.Identity.Client.OAuth2.TokenClient.SendHttpAndClearTelemetryAsync(String tokenEndpoint, ILoggerAdapter logger)
at Microsoft.Identity.Client.OAuth2.TokenClient.SendTokenRequestAsync(IDictionary`2 additionalBodyParameters, String scopeOverride, String tokenEndpointOverride, CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.Requests.ClientCredentialRequest.FetchNewAccessTokenAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.Requests.ClientCredentialRequest.ExecuteAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.Requests.RequestBase.RunAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.ApiConfig.Executors.ConfidentialClientExecutor.ExecuteAsync(AcquireTokenCommonParameters commonParameters, AcquireTokenForClientParameters clientParameters, CancellationToken cancellationToken)
at HIW.NotificationService.Service.GraphService.GetAccessToken() in C:\agent_work\60\s\HIW.NotificationService\Service\GraphService.cs:line 276

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.

asp.net core 3.1 antiforgery on docker - exceptiiion deserializing token

when i run my app on linux everything is fine,
but when i run it on docker i have following stack:
fail: Microsoft.AspNetCore.Antiforgery.DefaultAntiforgery[7]
An exception was thrown while deserializing the token.
Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException: The antiforgery token could not be decrypted.
---> System.Security.Cryptography.CryptographicException: The key {9f0347d0-eb7f-4e10-9b16-17c276c69737} was not found in the key ring.
at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.UnprotectCore(Byte[] protectedData, Boolean allowOperationsOnRevokedKeys, UnprotectStatus& status)
at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.DangerousUnprotect(Byte[] protectedData, Boolean ignoreRevocationErrors, Boolean& requiresMigration, Boolean& wasRevoked)
at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.Unprotect(Byte[] protectedData)
at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgeryTokenSerializer.Deserialize(String serializedToken)
--- End of inner exception stack trace ---
at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgeryTokenSerializer.Deserialize(String serializedToken)
at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgery.GetCookieTokenDoesNotThrow(HttpContext httpContext)
warn: Microsoft.AspNetCore.Session.SessionMiddleware[7]
Error unprotecting the session cookie.
System.Security.Cryptography.CryptographicException: The key {6209e3db-9865-4b93-96a2-8e0ea0f50d3a} was not found in the key ring.
at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.UnprotectCore(Byte[] protectedData, Boolean allowOperationsOnRevokedKeys, UnprotectStatus& status)
at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.DangerousUnprotect(Byte[] protectedData, Boolean ignoreRevocationErrors, Boolean& requiresMigration, Boolean& wasRevoked)
at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.Unprotect(Byte[] protectedData)
at Microsoft.AspNetCore.Session.CookieProtection.Unprotect(IDataProtector protector, String protectedText, ILogger logger)
and then after some 30 seconds
fail: Microsoft.AspNetCore.Server.Kestrel[13]
Connection id "0HLUJ4NPUIB4L", Request id "0HLUJ4NPUIB4L:00000001": An unhandled exception was thrown by the application.
System.AggregateException: One or more errors occurred. (A task was canceled.)
---> System.Threading.Tasks.TaskCanceledException: A task was canceled.
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at System.Threading.Tasks.Task`1.get_Result()
at RandevouApiCommunication.ApiQuery.PostSpecific[TResult,TQueryDto](String address, TQueryDto dto, AuthenticationHeaderValue auth)
at RandevouApiCommunication.Authentication.AuthenticationQuery.GetLoginAuthKey(String username, String password)
at RandevouMVC.Models.ApiQueryProvider.ApiQueryProvider.Login(String username, String password) in /app/RandevouMVC/Models/ApiQueryProvider/ApiQueryProvider.cs:line 34
at RandevouMVC.Models.Authentication.AuthenticationManager.Login(String username, String password) in /app/RandevouMVC/Models/Authentication/AuthenticationManager.cs:line 18
at RandevouMVC.Controllers.AuthenticationController.Login(UserLoginViewModel vm) in /app/RandevouMVC/Controllers/AuthenticationController.cs:line 47
at lambda_method(Closure , Object , Object[] )
at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)
i have looked over solutions but nothing helps...
my program.cs
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseKestrel(options=>{
options.ListenAnyIP(4444);
});
}
my startup.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDistributedMemoryCache();
services.AddSession(opts =>
{
opts.Cookie.IsEssential = true;
});
//services.AddDataProtection().DisableAutomaticKeyGeneration();
BusinessServices.Register(services);
services.AddMvc(config=>{
config.EnableEndpointRouting = false;
}).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app)
{
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
and finally my Dockerfile
FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build-env
WORKDIR /app
# Copy csproj and restore as distinct layers
#RUN cp /build/RandevouApiCommunication.dll ./RandevouMVC/
COPY ./*sln ./
COPY ./RandevouMVC/*.csproj ./RandevouMVC/
RUN dotnet restore
# Copy everything else and build
COPY . ./
RUN dotnet publish -c Release -o out
# Build runtime image
FROM mcr.microsoft.com/dotnet/core/aspnet:3.1
WORKDIR /app
COPY --from=build-env /app/out .
EXPOSE 4444
ENTRYPOINT ["dotnet", "RandevouMVC.dll"]
the problem fire when i send a post :"
namespace RandevouMVC.Controllers
{
[IgnoreAntiforgeryToken(Order = 1001)]
public class AuthenticationController : PrimaryController
{
private readonly IAuthenticationManager _authManager;
public AuthenticationController(IAuthenticationManager authManager)
{
_authManager = authManager;
}
[IgnoreAntiforgeryToken(Order = 1001)]
[HttpGet]
public ActionResult Index(ControllerActionResult result = null)
{
if (result?.Message != null)
ViewBag.OperationResult = result.Message;
var vm = new UserLoginViewModel
{
Login = string.Empty,
Password = string.Empty,
ApiKey = _ApiKey,
};
if (!string.IsNullOrWhiteSpace(_ApiKey))
{
vm.LoggedUser = _authManager.GetLoggedUser(_ApiKey)?.Name;
}
return View(vm);
}
[IgnoreAntiforgeryToken(Order = 1001)]
[HttpPost]
public IActionResult Login(UserLoginViewModel vm)
{
string apiKey = _authManager.Login(vm.Login, vm.Password);
if(string.IsNullOrWhiteSpace(apiKey))
{
var result = new ControllerActionResult { Message = "Nie udało się zalogować" };
return RedirectToAction("Index", result);
}
else
{
var result = new ControllerActionResult { Message = apiKey };
return RedirectToAction("Index", result);
// HttpContext.Session.SetString("ApiKey", apiKey);
// vm.LoggedUser = _authManager.GetLoggedUser(_ApiKey)?.Name;
// HttpContext.Session.SetString("UserName", vm.LoggedUser);
// return View("Index", vm);
}
}
}
what is more, if i don't call
_authManager.Login(vm.Login, vm.Password);
(it only sends post to api on localhost)
it works...
i don't need any antiforgery, i only use session to keep apiKey (received after logging in) on it, then i send it every request in headers
even if do sth like this in login method:
try{
apiKey = _authManager.Login(vm.Login, vm.Password);
}
catch(Exception ex)
{
var errresult = new ControllerActionResult { Message = ex.Message };
return RedirectToAction("Index", errresult);
}
i have to wait ~ 30 seconds and then i get same errors, and the Exception.Message is:
One or more errors occurred. (A task was canceled.)
can sb help me :) ?

OData v4 DefaultODataBatchHandler NotImplementedException

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.

Web API 2 with attribute routing getting same key error

Why do I keep getting the error below about duplicate keys? This worked fine before I tried attribute routing, but now it does not. If I remove {id:int} it always hits the second method, never the first, even if no ID is supplied.
EventsController
[System.Web.Http.RoutePrefix("api/v1/events")]
public partial class EventsController : System.Web.Http.ApiController
{
[System.Web.Http.Route("")]
public virtual ApiEventsResponse Get([FromUri] ApiEventsRequest request)
{
.....
return response;
}
[System.Web.Http.Route("{id:int}")]
public virtual ApiEventResponse Get(int id, [FromUri] ApiEventRequest request)
{
.....
return response;
}
Error when accessing /api/v1/events?id=12315
Server Error in '/' Application.
An item with the same key has already been added.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: An item with the same key has already been added.
Source Error:
Line 407: AreaRegistration.RegisterAllAreas();
Line 408:
Line 409: GlobalConfiguration.Configure(WebApiConfig.Register);
Line 410: RegisterRoutes(RouteTable.Routes);
Line 411:
Source File: f:\My Webs\BasketballTournaments\MainBranch\Websites\Tournaments\Global.asax.cs Line: 409
Stack Trace:
[ArgumentException: An item with the same key has already been added.]
System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) +52
System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add) +11187358
System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value) +10
System.Web.Http.Routing.InlineRouteTemplateParser.ParseRouteTemplate(String routeTemplate, IDictionary`2 defaults, IDictionary`2 constraints, IInlineConstraintResolver constraintResolver) +363
System.Web.Http.Routing.HttpRouteBuilder.BuildParsingRoute(String routeTemplate, Int32 order, IEnumerable`1 actions) +86
System.Web.Http.HttpConfigurationExtensions.MapHttpAttributeRoutesInternal(HttpConfiguration configuration, HttpRouteBuilder routeBuilder) +232
System.Web.Http.<>c__DisplayClass5.<MapHttpAttributeRoutes>b__4() +13
System.Web.Http.Routing.RouteCollectionRoute.EnsureInitialized(Func`1 initializer) +70
System.Web.Http.<>c__DisplayClass5.<MapHttpAttributeRoutes>b__3(HttpConfiguration config) +63
System.Web.Http.HttpConfiguration.EnsureInitialized() +23
System.Web.Http.GlobalConfiguration.Configure(Action`1 configurationCallback) +57
Tournaments.MvcApplication.OnApplicationStarted() in f:\My Webs\BasketballTournaments\MainBranch\Websites\Tournaments\Global.asax.cs:409
Ninject.Web.Common.NinjectHttpApplication.Application_Start() in c:\Projects\Ninject\Ninject.Web.Common\src\Ninject.Web.Common\NinjectHttpApplication.cs:82
[HttpException (0x80004005): An item with the same key has already been added.]
System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) +9903113
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +118
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +172
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +336
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +296
[HttpException (0x80004005): An item with the same key has already been added.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9882460
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254
WebApiConfig.cs
namespace Tournaments.App_Start
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Filters.Add(new ExceptionHandlingAttribute());
}
}
}
Not an answer but I just went back to my original. I think the original problem is I have two apis, and since you cant namespace web api routes yet there were duplicate key issues because the EventsController was listed twice but under different namespaces. That was the duplicate key issue, but for the {id:int} never working for a query string you got me.
routes.MapHttpRoute(
"DefaultApi",
"api/v{version}/{controller}/{id}",
new { id = RouteParameter.Optional, version = 1 }
);
routes.MapHttpRoute(
"DefaultApiAction",
"api/v{version}/{controller}/{action}"
);

Resources