在异常过滤器中获取WebApi异常响应

时间:2016-12-26 16:21:51

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

我们安装了一个例外过滤器

public class APIErrorHandlerAttribute : ExceptionFilterAttribute, IExceptionFilter
{
     // Sets up log4net logger
    private static readonly log4net.ILog log = log4net.LogManager.GetLogger
        (System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    public override void OnException(HttpActionExecutedContext context)
    {
        if (context.Exception is BusinessException)
        {
            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
            {
                Content = new StringContent(context.Exception.Message),
                ReasonPhrase = "Exception"
            });

        }

        //Log Critical errors
        log.Info("/****************** API Begin Error ******************/");
        log.Info("Exception:" + context.Exception + "  Case:" + CaseHelper.GetCurrentCaseID() + "  UserID:" + UserHelper.GetCurrentUserID());
        log.Info("/****************** API End Error ******************/");

        throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
        {
            Content = new StringContent(string.Format("Message: {0}\nStack Trace: {1}", context.Exception.Message, context.Exception.StackTrace)),
            ReasonPhrase = "Critical Exception",
        });
    }
}

适用于所有WebApi路线

    //*** Log API Error Globally using Log4net
    public static void RegisterFilters(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute("DefaultApiError", "api/{controller}/{action}/{id}", new { id = RouteParameter.Optional });
        config.Filters.Add(new LRAPIErrorHandlerAttribute());
    }

我们还有一个授权属性,我们将其附加到某些控制器。它看起来像这样:

public class LegalRadiusAPIAuthorizationAttribute : ActionFilterAttribute, IActionFilter, IFilter
{
    public string Permissions { get; set; }
    public string Roles { get; set; }
    public string Users { get; set; }

    public override void OnActionExecuted(HttpActionExecutedContext filterContext)
    {
        if (!HttpContext.Current.User.Identity.IsAuthenticated)
        {
            throw new HttpResponseException(HttpStatusCode.NonAuthoritativeInformation); //203
        }
     }
}

因此,如果未经身份验证的用户点击要求他登录的路线,我们就会抛出。如果我在此过滤器内调试并打开异常对话框,我可以在异常对象上看到以下属性:

enter image description here

如果我查看Response道具,我会看到抛出异常的所有相关细节。

问题是APIErrorHandlerAttribute处理此异常的时间。当异常到达处理程序时,我似乎无法在Response中找到异常的context.Exception属性...

enter image description here

即使在处理程序中,我从捕获的异常中收到以下错误消息:

  

处理HTTP请求导致异常。有关详细信息,请参阅此异常的“响应”属性返回的HTTP响应。

暗示上下文中的异常应具有该属性。

我觉得我有范围问题,并且过滤器中抛出的原始异常对象不在异常处理程序的context参数中。

2 个答案:

答案 0 :(得分:3)

您只需访问[System.Web.Http.HttpResponseException]中的context.Exception即可。为了做到这一点,并根据图片,您需要在right click[System.Web.Http.HttpResponseException]并在其上添加watcher。这将为您提供适当的casting,以便从context中检索信息。

enter image description here

答案 1 :(得分:0)

试试这个  var exceptionData = new ExceptionData { Name = "exception name", Message = "exception message" }; Content = new ObjectContent<ExceptionData>(exceptionData, JsonFormatter),

相关问题