我正在尝试弄清楚如何在.NET WebApi2中实现全局异常处理程序。
我尝试遵循微软在这里提供的示例:https://docs.microsoft.com/en-us/aspnet/web-api/overview/error-handling/web-api-global-error-handling
但当异常发生时,它什么也不做。
这是我的代码:
public class GlobalExceptionHandler : ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{
Trace.WriteLine(context.Exception.Message);
context.Result = new TextPlainErrorResult
{
Request = context.ExceptionContext.Request,
Content = "Oops! Sorry! Something went wrong." +
"Please contact support@testme.com so we can try to fix it."
};
}
private class TextPlainErrorResult : IHttpActionResult
{
public HttpRequestMessage Request { private get; set; }
public string Content { private get; set; }
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response =
new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent(Content),
RequestMessage = Request
};
return Task.FromResult(response);
}
}
}有没有更好的方法(或更合适的方法)来实现全局异常处理程序?
发布于 2017-05-13 18:34:24
尝试将其添加到您的WebApiConfig
webConfiguration.Services.Replace(typeof(IExceptionHandler), new MyExceptionHandler()); // You have to use Replace() because only one handler is supported
webConfiguration.Services.Add(typeof(IExceptionLogger), new MyExceptionLogger()); // webConfiguration is an instance of System.Web.Http.HttpConfiguration发布于 2017-08-12 00:21:18
你错过了
class GlobalExceptionHandler : ExceptionHandler
{
public override bool ShouldHandle(ExceptionHandlerContext context)
{
return true;
}
//...
}https://stackoverflow.com/questions/43952014
复制相似问题