使用全局exceptionhandeling搞砸了DelegatingHandler
当遍历IExceptionHandler时,当发生意外exception时,响应不会到达DelegatingHandler。 我怎样才能解决这个问题?
在webapi 2中,我想为请求和响应消息实现审计记录器。 我还想添加一个全局exception处理程序。 但是,当我用我的自定义实现替换IExceptionHandler时。 响应永远不会到达DelegatingHandler -onexception – 因此对响应的审计将丢失。
在WebApiConfig中
// add custom audittrail logger config.MessageHandlers.Add(new AuditLogHandler()); // replace global exception handeling config.Services.Replace(typeof(IExceptionHandler), new WebAPiExceptionHandler());
自定义exception处理程序
public class WebAPiExceptionHandler : ExceptionHandler { //A basic DTO to return back to the caller with data about the error private class ErrorInformation { public string Message { get; set; } public DateTime ErrorDate { get; set; } } public override void Handle(ExceptionHandlerContext context) { context.Result = new ResponseMessageResult(context.Request.CreateResponse(HttpStatusCode.InternalServerError, new ErrorInformation { Message = "Iets is misgegaan", ErrorDate = DateTime.UtcNow })); } }
自定义Auditlogger
public class AuditLogHandler : DelegatingHandler { protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { if (request.Content != null) { var task = await request.Content.ReadAsStringAsync(); // .. code for loggign request } var result = await base.SendAsync(request, cancellationToken); // .. code for logging response // when I do not replace WebAPiExceptionHandler, code is reachred here // When I Do use WebAPiExceptionHandler, code is not reached here return result; } }
在webapi中抛出exception的代码
public class Values_v2Controller : ApiController { public string Get(int id) { throw new Exception("haha"); } }
不要使用ExceptionHandler作为基类,实现接口IExceptionHandler
public class WebAPiExceptionHandler : IExceptionHandler { public Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken) { var fout = new ErrorInformation { Message = "Iets is misgegaan" , ErrorDate = DateTime.UtcNow }; var httpResponse = context.Request.CreateResponse(HttpStatusCode.InternalServerError, fout); context.Result = new ResponseMessageResult(httpResponse); return Task.FromResult(0); } private class ErrorInformation { public string Message { get; set; } public DateTime ErrorDate { get; set; } } }
问题是,如果ShouldHandle(ExceptionHandlerContext context)
返回true, ExceptionHandler
只执行Handle(ExceptionHandlerContext context)
方法。
覆盖bool ShouldHandle(ExceptionHandlerContext context)
总是返回true为我修复问题。
上述就是C#学习教程:使用全局exceptionhandeling搞砸了DelegatingHandler分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1005528.html