Catching HttpRequestValidationException with ExceptionHandler

0

Using ASP.NET WebApi 2, Why can't I catch HttpRequestValidationException in my Global ExceptionHandler or Global ExceptionLogger?

Error is: [HttpRequestValidationException (0x80004005): A potentially dangerous Request.QueryString value was detected from the client...]

Using Application_Error works fine, HttpRequestValidationException can be caught fine.

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);
        }
    }
}
asp.net
exception-handling
asked on Stack Overflow Nov 1, 2018 by Porton

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0