asp.net - web api TaskScheduler.UnobservedTaskException

标签 asp.net .net asp.net-web-api task-parallel-library

我最近向生产网站发布了一个 ASP.NET Web API。在生产中,大约每天一次,未处理的异常会导致网站进程回收:

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)

此异常似乎并非源自程序代码,而是源自 Web API 内部。我需要防止这种异常回收进程,因为这会破坏大量用户的 session 。

我知道处理此异常的一种方法是使用:

TaskScheduler.UnobservedTaskException += (sender, e) =>
{
    McpsEventLog.PostException(e.Exception, "webapicontroller");
    e.SetObserved();
};

但是为了让它工作,我可以把这段代码放在哪里。在 web api Controller 的某个地方?或者在 global.asax 中。有人知道如何在 asp.net Web Api Rest 服务中实现 UnobserveredTaskException 吗?

最佳答案

你是对的:在 Web 应用程序的上下文中,未处理的异常是 Not Acceptable 。设置该处理程序的正确位置是 Application_Start 事件。

您还应该设置UnhandledException-event 。但它不允许您接受异常。仅记录它。

最后,请参阅我关于此主题的问题:How to treat unhandled thread-exceptions in ASP.NET?我没有得到可用的答案,但它可能仍然对您有帮助。

关于asp.net - web api TaskScheduler.UnobservedTaskException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12169230/

相关文章:

c# - 绑定(bind)列表到 GridView

c# - ASP.NET 中的文本多重搜索

c# - wpf、c#、viewport3D 的 renderTargetBitmap 没有将其分配给窗口

c# - 如何限制 Web Api 中的请求?

c# - 网络 API : different way of attribute routing

c# - ASP.net Identity Framework - 重新发送确认电子邮件

c# - 如何在 10 美元和 50.58 美元之间划线

c# - ActiveX 控件在 WPF 应用程序的设计时被禁用

c# - 从 System.Drawing.Imaging.ImageFormat (C#) 获取扩展

asp.net-web-api - 在没有身份的情况下使用 Bearer/Jwt 授权