我已经为我的 Web API 实现了一个自定义异常过滤器。它按预期工作,除了一个小细节......
在以下代码示例中,SaveToErrorLog 保存异常详细信息并尝试从 context.Request.RawUrl 获取请求 url。但是 context.Request 不包含异常发生时 API 尝试提供的 url。使用这样的异常过滤器时,有没有办法获取 url?
public class APIExceptionFilter : ExceptionFilterAttribute
{
private HttpContextBase context;
public APIExceptionFilter()
{
context = new HttpContextWrapper(HttpContext.Current);
}
public override void OnException(HttpActionExecutedContext actionContext)
{
actionContext.Response = new HttpResponseMessage(HttpStatusCode.InternalServerError);
if (actionContext != null && context != null)
{
facade.SaveToErrorLog(actionContext.Exception, context.Request);
}
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent(actionContext.Exception.Message),
ReasonPhrase = "APIException"
});
}
}