首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用全局异常处理会扰乱DelegatingHandler

使用全局异常处理会扰乱DelegatingHandler
EN

Stack Overflow用户
提问于 2017-03-24 09:24:32
回答 2查看 1.6K关注 0票数 2

当ovveride进行IExceptionHandler时,当发生意外异常时,响应不会到达DelegatingHandler。我怎么才能解决这个问题?

在webapi 2中,我想为请求和响应消息实现一个审计记录器。我还想添加一个全局异常处理程序。但是,当我用自定义实现替换IExceptionHandler时。响应永远不会到达DelegatingHandler -on异常,因此响应的审计将丢失。

在WebApiConfig中

代码语言:javascript
复制
// add custom audittrail logger
config.MessageHandlers.Add(new AuditLogHandler());
// replace global exception handeling
config.Services.Replace(typeof(IExceptionHandler), new WebAPiExceptionHandler());

自定义异常处理程序

代码语言:javascript
复制
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 }));
    }
}

定制审计记录器

代码语言:javascript
复制
public class AuditLogHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> 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中抛出异常的代码

代码语言:javascript
复制
public class Values_v2Controller : ApiController
{
    public string Get(int id)
    {
        throw new Exception("haha");
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-03-27 08:44:45

不要使用ExceptionHandler作为基类,实现接口IExceptionHandler

代码语言:javascript
复制
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; }
    }
}
票数 1
EN

Stack Overflow用户

发布于 2017-08-16 00:39:23

问题是,ExceptionHandler只在Handle(ExceptionHandlerContext context)返回true时才执行ShouldHandle(ExceptionHandlerContext context)方法。

重写bool ShouldHandle(ExceptionHandlerContext context),始终返回true,为我修复问题。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42995678

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档