在ASP.NETWebApi中使用“ExceptionHandler”需要一个完整的示例来处理未处理的异常吗?我检查了这个链接http://www.asp.net/web-api/overview/web-api-routing-and-actions/web-api-global-error-handling。在这个链接中,他们提到了这个类OopsExceptionHandler:ExceptionHandler{publicoverridevoidHandleCore(ExceptionHandlerContextcontext){context.Result=newTextPlainErrorResult{Request=context.ExceptionContext.Request,Content=“糟糕!抱歉!出了点问题。”+“请联系support@contoso.com,以便我们尝试修复它。”};}privateclassTextPlainErrorResult:IHttpActionResult{publicHttpRequestMessageRequest{get;放;}公共字符串内容{得到;放;}publicTaskExecuteAsyncen(CancellationcancellationToken){HttpResponseMessageresponse=newHttpResponseMessage(HttpStatusCode.InternalServerError);response.Content=newStringContent(Content);response.RequestMessage=请求;返回Task.FromResult(Webresponse);这个类在行动中被调用。所以任何人都可以使用这个ExceptionHandler给我完整的示例。在您的WebApi配置中,您需要添加以下行:config.Services.Replace(typeof(IExceptionHandler),newOopsExceptionHandler());还要确保您已经创建了一个实现IExceptionHandler的基础ExceptionHandler类:publicclassExceptionHandler:IExceptionHandler{publicvirtualTaskHandleAsync(ExceptionHandlerContextcontext,CancellationTokencancellationToken){if(!ShouldHandle(context)){returnTask.FromResult(0);}返回HandleAsyncCore(上下文,取消令牌);}publicvirtualTaskHandleAsyncCore(ExceptionHandlerContextcontext,CancellationTokencancellationToken){HandleCore(context);返回Task.FromResult(0);}publicvirtualvoidHandleCore(ExceptionHandlerContextcontext){}publicvirtualboolShouldHandle(ExceptionHandlerContextcontext){returncontext.CatchBlock.IsTopLevel;请注意,这只会处理其他地方未处理的异常(例如通过exceptionfilter)。您不需要自己实现IExceptionHandler低级机制。相反,您可以简单地从ExceptionHandler继承并覆盖Handle方法。publicclassMyExceptionHandler:ExceptionHandler{publicoverridevoidHandle(ExceptionHandlerContextcontext){//TODO:做你需要做的事情base.Handle(context);}}ExceptionHandler实现IExceptionHandler并管理基本的核心机制,如异步和应处理的异常)。像这样使用您的异常处理程序:config.Services.Replace(typeof(IExceptionHandler),newMyExceptionHandler());资源本页解释了如何实现IExceptionHandler,但是有一些拼写错误,并且代码没有反映最新版本的WebApi。没有关于System.Web.Http.ExceptionHandling命名空间的文档(关于NuDoq)。所以..使用.NET程序集反编译器查看GitHub上的源代码,我看到ExceptionHandler类实现了IExceptionHandler并具有一些虚拟方法。ExceptionHandler看起来像这样:namespaceSystem.Web.Http.ExceptionHandling{///表示未处理的异常处理程序。publicabstractclassExceptionHandler:IExceptionHandler{///返回。任务IExceptionHandler.HandleAsync(ExceptionHandlerContextcontext,CancellationTokencancellationToken){if(context==null){thrownewArgumentNullException("context");}ExceptionContextarg_14_0=context.ExceptionContext;如果(!this.ShouldHandle(context)){返回TaskHelpers.Completed();}返回this.HandleAsync(context,cancellationToken);}///在派生类中重写时,异步处理异常。///代表异步异常处理操作的任务。///异常处理上下文。///用于监视取消请求的令牌。publicvirtualTaskHandleAsync(ExceptionHandlerContextcontext,CancellationTokencancellationToken){this.Handle(context);返回TaskHelpers.Completed();}///当overridden在派生类中,同步处理异常。///异常处理上下文。publicvirtualvoidHandle(ExceptionHandlerContextcontext){}///确定是否应该处理异常。///如果应该处理异常则为真;否则,假的。///异常处理上下文。publicvirtualboolShouldHandle(ExceptionHandlerContextcontext){if(context==null){thrownewArgumentNullException("context");}ExceptionContextexceptionContext=context.ExceptionBlockContext;ExceptionContextCexceptionContext.CatchBlock;返回catchBlock.IsTopLevel;可以清楚的看到,HandleAsync是用ExceptionContextCatchBlock.IsTopLevel实现的,HandleAsync调用Handle?我希望这会有所帮助,直到根据JonSusiak的回答发布完整文档,您需要使用:config.Services.Replace(typeof(IExceptionHandler),newOopsExceptionHandler());请注意替换调用,而不是添加。原因在于此链接中的文章:ASP.NETWebAPI2中的全局错误处理方案概述我们提供了两个新的用户可替换服务IExceptionLogger和IExceptionHandler来记录和处理未处理的异常。服务非常相似,有两个主要区别:我们支持注册多个异常记录器,但只支持一个异常处理程序。由于默认情况下已经注册了一个处理程序,因此无法添加其他处理程序。publicDefaultServices(HttpConfigurationconfiguration){if(configuration==null)throwSystem.Web.Http.Error.ArgumentNull("configuration");this._configuration=配置;this.SetSingle((IActionValueBinder)newDefaultActionValueBinder());this.SetSingle((IApiExplorer)newApiExplorer(configuration));this.SetSingle((IAssembliesResolver)newDefaultAssembliesResolver());this.SetSingle((IBodyModelValidator)newDefaultBodyModelValidator());this.SetSingle((IContentNegotiator)newDefaultContentNegotiator());this.SetSingle((IDocumentationProvider)null);this.SetMultiple((IFilterProvider)newConfigurationFilterProvider(),(IFilterProvider)newActionDescriptorFilterProvider());this.SetSingle((IHostBufferPolicySelector)null);this.SetSingle((IHttpActionInvoker)newApiControllerActionInvoker());this.SetSingle((IHttpActionSelector)newApiControllerActionSelector());this.SetSingle((IHttpControllerActivator)新的DefaultHttpControlleundefinedidatorProvider)newDataMemberModelValidatorProvider());this.SetMultiple((ValueProviderFactory)newQueryStringValueProviderFactory(),(ValueProviderFactory)newRouteDataValueProviderFactory());this.SetSingle((IModelValidatorCache)newModelValidatorCache(newLazy)>((Func>=>ServicesExtensions.GetModelValidatorProviders((ServicesContainer)this)))));this.SetSingle((IExceptionHandler)newDefaultExceptionHandler());这个.SetMultiple();this._serviceTypesSingle=newHashSet((IEnumerable)this._defaultServicesSingle.Keys);this._serviceTypesMulti=newHashSet((IEnumerable)this._defaultServicesMulti.Keys);这个.ResetCache();您可以从WebAPI团队查看以下示例:http://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/Elmah/ReadMe.txt以上是C#学习教程:Using"ExceptionHandler"inASP.NETWebApi需要一个完整的示例来处理未处理的异常吗?分享的所有内容,如果对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
