使用全局异常处理搞砸了DelegatingHandler [英] using global exception handeling messes up DelegatingHandler

查看:218
本文介绍了使用全局异常处理搞砸了DelegatingHandler的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ovveride IExceptionHandler上运行时,发生意外异常时响应不会到达DelegatingHandler。如何解决此问题?

When ovveride the IExceptionHandler, the response does not reach the DelegatingHandler when a unexpected exception occurs. How can I fix this?

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

In webapi 2, I want to implement a audit logger for request and response messages. I also want to add a global exception handler. However, when I replace the IExceptionHandler with my custom implementation. the response never reaches the DelegatingHandler -on exception - And thus the audit for response is lost.

在WebApiConfig中

in WebApiConfig

// add custom audittrail logger
config.MessageHandlers.Add(new AuditLogHandler());
// replace global exception handeling
config.Services.Replace(typeof(IExceptionHandler), new WebAPiExceptionHandler());

自定义异常处理程序

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 }));
    }
}

自定义审核记录器

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中引发异常的代码

Code for throwing exception in webapi

public class Values_v2Controller : ApiController
{
    public string Get(int id)
    {
        throw new Exception("haha");
    }
}


推荐答案

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

Dont use ExceptionHandler as base class, implement interface 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; }
    }
}

这篇关于使用全局异常处理搞砸了DelegatingHandler的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆