I have recently published an asp.net web api to a production web site. On production about once a day the an unhandled exception causes the web site process to recycle:
An unhandled exception occurred and the process was terminated. Application ID: /LM/W3SVC/2/ROOT/oasis Process ID: 9236 Exception: System.AggregateException Message: A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread. StackTrace: at System.Threading.Tasks.TaskExceptionHolder.Finalize() InnerException: System.Web.HttpException Message: The remote host closed the connection. The error code is 0x800704CD. StackTrace: at System.Web.Http.WebHost.HttpControllerHandler.EndProcessRequest(IAsyncResult result) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
This exception appears to not to originate in program code but in web api internals. I need to prevent such an excetion from recycling the process as this destroys the sessions of numberous users.
I understand that one way to handle this exception is to use :
TaskScheduler.UnobservedTaskException += (sender, e) =>
{
McpsEventLog.PostException(e.Exception, "webapicontroller");
e.SetObserved();
};
But for this to work, where can I put this code. somewhere in the web api controller? Or in the global.asax. Does someone know how the UnobserveredTaskException can be impletmented in an asp.net Web Api rest service?