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

3
我们安装了一个异常过滤器。
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请求的处理导致异常。有关详细信息,请参阅此异常的“Response”属性返回的HTTP响应。
这意味着上下文中的异常应该具有该属性。
我觉得我遇到了范围问题,并且在异常过滤器中抛出的原始异常对象不在异常处理程序的“context”参数中。

如果您点击[System.Web.Http.HttpResponseException]上的“加号”图标呢? - Hackerman
您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - seebiscuit
只需右键单击它并添加另一个观察即可。这将为您提供适当的转换,以便从上下文中检索信息 :) - Hackerman
搞定了,@Hackerman!请将其写成答案,以便我可以标记为已接受 :D - seebiscuit
考虑到这个问题,明天的第一时间就能完成 :) - Hackerman
完成了!大家周末愉快!! - Hackerman
2个回答

3
你只需要从context.Exception中访问[System.Web.Http.HttpResponseException]。为了实现这一点,并根据图片,您需要在[System.Web.Http.HttpResponseException]右键单击并在其上添加一个watcher。这将为您提供适当的casting,以便从context中检索信息。

enter image description here


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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接