使用ASP.NET WebApi 2, 为什么在我的Global ExceptionHandler或Global ExceptionLogger中无法捕获HttpRequestValidationException?
错误是:[HttpRequestValidationException(0x80004005):从客户端检测到潜在的危险Request.QueryString值...]
使用Application_Error可以正常工作,可以很好地捕获HttpRequestValidationException。
WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
//...stuffs
//Global exception handler
config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler());
//add global error logger
config.Services.Add(typeof(IExceptionLogger), new GlobalExceptionLogger());
}
public class GlobalExceptionLogger : ExceptionLogger
{
public override void Log(ExceptionLoggerContext context)
{
//This does not handle HttpRequestValidationException
Exception exception = context.ExceptionContext.Exception;
//.....
}
}
public class GlobalExceptionHandler : ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{
//This does not handle HttpRequestValidationException either ...
var result = new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent("An unexpected error occured. Please notify your administrator"),
ReasonPhrase = "Unexpected Error"
};
context.Result = new UnhandledExceptionResult(context.Request, result);
}
public class UnhandledExceptionResult : IHttpActionResult
{
private HttpRequestMessage _request;
private HttpResponseMessage _httpResponseMessage;
public UnhandledExceptionResult(HttpRequestMessage request, HttpResponseMessage httpResponseMessage)
{
_request = request;
_httpResponseMessage = httpResponseMessage;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
return Task.FromResult(_httpResponseMessage);
}
}
}