IConfidentialClientApplication AcquireTokenForClient exception being thrown periodically - microsoft-graph-api

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

Related

Accessing user info through Microsoft graph API

Scenario - Frontend will login to microsoft and will give access token to backend, with that token I am unable to create microsoft graph api instance.
I am trying to access the user data using microsoft graph api and I receive this error.
Status Code: Unauthorized
Microsoft.Graph.ServiceException: Code: InvalidAuthenticationToken
Message: Access token validation failure. Invalid audience.
Inner error:
AdditionalData:
date: 2020-09-30T11:00:43
request-id: -8561--aebc-ff72e69942c4
client-request-id: -8561-4fb2-aebc-
ClientRequestId: c4f169bb-8561-4fb2-aebc-
at Microsoft.Graph.HttpProvider.SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
at Microsoft.Graph.BaseRequest.SendRequestAsync(Object serializableObject, CancellationToken cancellationToken, HttpCompletionOption completionOption)
at Microsoft.Graph.BaseRequest.SendAsync[T](Object serializableObject, CancellationToken cancellationToken, HttpCompletionOption completionOption)
at Microsoft.Graph.UserRequest.GetAsync(CancellationToken cancellationToken)
at OptimusPortal.Controllers.WeatherForecastController.GetAsync() in C:\Users\bippan.kumar\Documents\GitHub\OIC\OptimusPortal\OptimusPortal\Controllers\WeatherForecastController.cs:line 52
at lambda_method(Closure , Object )
at Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable.Awaiter.GetResult()
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
My ConfigureServices function in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
.AddAzureADBearer(options => Configuration.Bind("AzureAd", options));
string token;
services.Configure<JwtBearerOptions>(AzureADDefaults.JwtBearerAuthenticationScheme, options =>
{
options.SaveToken = true;
options.Events = new JwtBearerEvents
{
OnTokenValidated = OnTokenValidated
};
options.Authority += "/v2.0";
options.Audience = "api://xyz";
options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
//I have kept these settings in place to provide easy support for docker.
ValidateIssuer = false,
ValidateAudience = false
};
});
services.AddControllers();
}
Function where I am creating GraphServiceClient instance. Error is thrown at last line of code in this function.
[HttpGet]
public async Task<IEnumerable<WeatherForecast>> GetAsync()
{
var token = await HttpContext.GetTokenAsync("access_token");
GraphServiceClient graphServiceClient =
new GraphServiceClient(new DelegateAuthenticationProvider(async (requestMessage) =>
{
requestMessage.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", token);
})
);
// Make a Microsoft Graph API query
// Error is thrown at this line of code
var users = await graphServiceClient.Me.Request().GetAsync();
}

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.

How to timeout a request in ASP.net MVC web api

My application is running ASP.Net MVC 5.2.2 and hosted on the IIS 7 integrated pipeline. I am looking to timeout requests when the duration of the request is over 3 minutes. Setting the httpRuntime.executionTimeout does not help.
I have other ASP.Net applications running in IIS 6 classic mode. Asp.Net automatically throws a ThreadAbortException when the request duration exceeds the httpRuntime.executionTimeout value.
I tried to look into the ASP.Net source code and found RequestTimeoutManager. It basically keeps track of all the HttpRequests initialized and a background task aborts the requests exceeding the time out duration. Is RequestTimeoutManager applicable for ASP.Net MVC Web Api? If not how can something similar be implemented.
Stack Trace for a typical Http Request in my application
at MyApp.Api.Controllers.Controller.GetDetails(String Id)
at lambda_method(Closure , Object , Object[] )
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass13.<GetExecutor>b__c(Object instance, Object[] methodParameters)
at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
at System.Web.Http.Controllers.ApiControllerActionInvoker.<>c__DisplayClass3.<InvokeActionAsync>b__0()
at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)
at System.Web.Http.Controllers.ApiControllerActionInvoker.InvokeActionAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
at System.Web.Http.Filters.ActionFilterAttribute.System.Web.Http.Filters.IActionFilter.ExecuteActionFilterAsync(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.Threading.Tasks.TaskHelpersExtensions.ThenImpl[TTask,TOuterResult](TTask task, Func`2 continuation, CancellationToken cancellationToken, Boolean runSynchronously)
at System.Threading.Tasks.TaskHelpersExtensions.Then[TOuterResult](Task task, Func`1 continuation, CancellationToken cancellationToken, Boolean runSynchronously)
at System.Web.Http.ApiController.<>c__DisplayClass3.<ExecuteAsync>b__0()
at System.Web.Http.Filters.AuthorizationFilterAttribute.System.Web.Http.Filters.IAuthorizationFilter.ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func`1 continuation)
at System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)
at System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncInternal(HttpRequestMessage request, CancellationToken cancellationToken)
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 MyApp.Common.MyAppExceptionHandler.<>n__0(HttpRequestMessage request, CancellationToken cancellationToken)
at MyApp.Common.MyAppExceptionHandler.<SendAsync>d__1.MoveNext() in C:\MyApp_source\Components\MyAppExceptionHandler.cs
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine& stateMachine)
at MyApp.Common.MyAppExceptionHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.DelegatingHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Web.Http.HttpServer.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpMessageInvoker.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Web.Http.WebHost.HttpControllerHandler.BeginProcessRequest(HttpContextBase httpContextBase, AsyncCallback callback, Object state)
at System.Web.HttpApplication.CallHandlerExecutionStep.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)
You can use Custom attribute to override timeout value in AsyncManager
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CustomAsyncTimeoutAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException(nameof(filterContext));
}
if (!(filterContext.Controller is IAsyncManagerContainer managerContainer))
{
throw new InvalidOperationException("Action Filter failed");
}
managerContainer.AsyncManager.Timeout = 180000;
base.OnActionExecuting(filterContext);
}
}
Or why can't you use [AsyncTimeout(180000)] ?
You can create a race between 2 running tasks, one for the main operation, and another for preferred timeout (e.g 3 * 60,000 ms = 180,000 ms) by the following code :
public async Task<HttpResponseMessage> Get()
{
var _task = this.DoTask(2000); //your operation required time
var _timeout = this.SetTimeout(180000); //equal to 3 minutes
var _finishedTask = await Task.WhenAny(_timeout, _task);
if (_finishedTask == _timeout)
return this.Request.CreateResponse(HttpStatusCode.RequestTimeout); //timeout
else
return this.Request.CreateResponse(HttpStatusCode.OK, _task.Result); //Ok
}
private async Task<string> DoTask(int duration)
{
await Task.Delay(duration);
return "work results";
}
private async Task SetTimeout(int ms)
{
await Task.Delay(ms);
}
I have tested with ApiController as base class and works fine. The task which is finished earlier win the race and determines the Api result.

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

ArgumentNullException when streaming files via WCF

I have a WCF streaming binary files. Below is a shortened version of the contract.
[MessageContract()]
public class DocumentTransfer
{
[MessageHeader(MustUnderstand = true)]
public string Title { get; set; }
[MessageHeader(MustUnderstand = true)]
public string FileName { get; set; }
[MessageBodyMember(Order = 1)]
public System.IO.Stream Data;
}
Everything works fine but there are scenarios when only some other values associated with the file need to be updated but not the file itself. In that case the client sets Data = null. The Data property then cannot be interpreted/serialized and throws this exception:
System.ServiceModel.Dispatcher.StreamFormatter.Serialize(XmlDictionaryWriter writer, Object[] parameters, Object returnValue)
System.ServiceModel.Dispatcher.OperationFormatter.SerializeBodyContents(XmlDictionaryWriter writer, MessageVersion version, Object[] parameters, Object returnValue, Boolean isRequest)
System.ServiceModel.Dispatcher.OperationFormatter.OperationFormatterMessage.OperationFormatterBodyWriter.OnWriteBodyContents(XmlDictionaryWriter writer)
System.ServiceModel.Channels.BodyWriter.WriteBodyContents(XmlDictionaryWriter writer)
System.ServiceModel.Channels.BodyWriterMessage.OnWriteBodyContents(XmlDictionaryWriter writer)
System.ServiceModel.Channels.Message.OnWriteMessage(XmlDictionaryWriter writer)
System.ServiceModel.Channels.Message.WriteMessage(XmlDictionaryWriter writer)
System.ServiceModel.Channels.TextMessageEncoderFactory.TextMessageEncoder.WriteMessage(Message message, Stream stream)
System.ServiceModel.Channels.HttpOutput.WriteStreamedMessage(TimeSpan timeout)
System.ServiceModel.Channels.HttpOutput.Send(TimeSpan timeout)
System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.SendRequest(Message message, TimeSpan timeout)
System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)
System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
...UploadDocument(DocumentTransfer request)
...UploadDocument(DocumentTransfer request) in ...
Any ideas guys?
You are getting the error in SerializeBodyContents when the body is null.
You can either create a different operation for when you do not have a file, or put a byte in the stream to avoid the exception. The first of these options is preferable, the last if you cannot change the contract.
Another option would be to return Stream.Null.

Resources