如何在BaseAPIController中处理Web API 1.0中的异常

时间:2015-06-16 02:08:27

标签: .net asp.net-web-api

我目前正在使用Web API 1.0和.NET 4.0 我需要一个能够处理我的Base API中捕获和处理异常的噪音的函数,这样我就不需要在每个RESTful操作中编写它。

 public int Get(WelcomeTeamNotes note)
    {

        try
        {
            return _customerService.UpdateNotes(note);
        }
        catch (Exception ex)
        {
            log.Error("CustomerController : _customerService.UpdateNotes(note)", ex);
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }
    }

使用Log4net记录错误。我已经在Web API 2.0中看到过这样的实现,但是没有获得1.0的实现。

1 个答案:

答案 0 :(得分:0)

你可能应该使用异常过滤器。

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
    public sealed class ExceptionHandlerAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            base.OnActionExecuted(actionExecutedContext);

            var e = actionExecutedContext.Exception;
            if (e != null)
            {
                // do whatever you need with your exception
            }

        }

您可以将此属性放在某些控制器上,也可以在全局配置中注册,以便一次性覆盖它们。

protected void Application_Start()
{
    GlobalConfiguration.Configuration.Filters.Add(new ExceptionHandlerAttribute());

    ...
}