C# WebApi 异常处理解决方案

2019-12-30 19:54:33于海丽

定义好了异常处理方法,剩下的就是如何使用了。可以根据实际情况,在不同级别使用统一的异常处理机制。

1、接口级别


[WebApiExceptionFilter]
    [HttpGet]
    public string GetAllChargingData([FromUri]TB_CHARGING obj)
    {
      throw new NotImplementedException("方法不被支持");
    }

执行到异常后,会先进到OnException方法:

C#,WebApi,异常处理

执行完成之后浏览器查看:

C#,WebApi,异常处理

如果需要,甚至可以向Status Code里面写入自定义的描述信息,并且还可以向我们的Response的Content里面写入我们想要的信息。我们稍微改下OnException方法:


if (actionExecutedContext.Exception is NotImplementedException)
      {
        var oResponse = new HttpResponseMessage(HttpStatusCode.NotImplemented);
        oResponse.Content = new StringContent("方法不被支持");
        oResponse.ReasonPhrase = "This Func is Not Supported";
        actionExecutedContext.Response = oResponse;
      }

看看ReasonPhrase描述信息