我们安装了一个异常过滤器。
我们还有一个授权属性,我们会将其附加到某些控制器上。它看起来类似于这样:
问题是当
这意味着上下文中的异常应该具有该属性。
我觉得我遇到了范围问题,并且在异常过滤器中抛出的原始异常对象不在异常处理程序的“context”参数中。
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
}
}
}
所以,如果未经身份验证的用户访问需要登录的路由,则会抛出异常。如果我在此过滤器中进行调试并打开异常对话框,则可以看到异常对象上的以下属性:
如果我查看 Response
属性,我会看到抛出异常的所有相关细节。问题是当
APIErrorHandlerAttribute
处理此异常时。当异常传递到处理程序时,我似乎找不到异常中 Response
属性在 context.Exception
中...
尽管在处理程序中,我从捕获的异常中获取以下错误消息:
HTTP请求的处理导致异常。有关详细信息,请参阅此异常的“Response”属性返回的HTTP响应。这意味着上下文中的异常应该具有该属性。
我觉得我遇到了范围问题,并且在异常过滤器中抛出的原始异常对象不在异常处理程序的“context”参数中。
[System.Web.Http.HttpResponseException]
上的“加号”图标呢? - Hackerman