예기치 않은 예외가 발생하면 응답이 IExceptionHandler를 ovveride하면 DelegatingHandler에 도달하지 않습니다. 이 문제를 어떻게 해결할 수 있습니까?전역 예외 처리를 사용하면 위임됩니다. DelegatingHandler
webapi 2에서 요청 및 응답 메시지에 대해 감사 로거를 구현하려고합니다. 또한 전역 예외 처리기를 추가하려고합니다. 그러나 IExceptionHandler를 사용자 정의 구현으로 바꿀 때. 응답은 DelegatingHandler에 도달하지 않습니다. 예외적으로 - 따라서 응답에 대한 감사는 손실됩니다.
// 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 }));
}
}
사용자 정의 Auditlogger
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에 예외를 던지는에 대한
public class Values_v2Controller : ApiController
{
public string Get(int id)
{
throw new Exception("haha");
}
}
WebApiConfig
에서
왜 이것이 효과가 있는지 설명 할 수 있습니까? –