【问题标题】:Global Exception Handling Web Api 2全局异常处理 Web API 2
【发布时间】:2017-10-12 14:47:59
【问题描述】:

我正在尝试弄清楚如何在 .NET Web Api 2 中实现全局异常处理程序。

我尝试按照 Microsoft 在此处列出的示例进行操作: 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);
            }
        }
    }

有没有更好的方法(或更合适的方法)来实现全局异常处理程序?

【问题讨论】:

  • 如果它在你的情况下不起作用,你可以实现Exception Filters来处理异常。
  • "...更好的方式(或更合适的方式)...." 受制于意见,可悲的是,SO 偏离主题。 How to Ask

标签: c# asp.net asp.net-web-api2


【解决方案1】:

尝试将此添加到您的 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

【讨论】:

    【解决方案2】:

    你错过了

    class GlobalExceptionHandler : ExceptionHandler
    {
        public override bool ShouldHandle(ExceptionHandlerContext context)
        {
            return true;
        }
        //...
    }
    

    WebApi v2 ExceptionHandler not called

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-19
      • 2019-02-05
      • 1970-01-01
      • 2015-01-02
      • 2016-11-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多