5
votes

My MVC 5 web application running on Azure Cloud Service crashed with an unhandled exception "A potentially dangerous Request.Path value was detected from the client (:)".

The cause for this crash was some third party (maybe malicious) hit my endpoints with url: http://myExampleHost.com/m:443/templates

The colon in the url cannot pass the path validation.

Some answers (A potentially dangerous Request.Path value was detected from the client (*)) suggest change the validate rules. However, out of security concerns, we may not want to compromise on this.

The ideal behavior for it that: we catch the exception, log it and return some error messages without crashing. How should we do that?

A more general question on this would be: how to catch an exception before the request hits controllers in MVC?

1

1 Answers

5
votes

The ideal behavior for it that: we catch the exception, log it and return some error messages without crashing. How should we do that?

Per my understanding, you could leverage the Application_Error event to capture unhandled exception(s) within ASP.NET. Here is my test, you could refer to it:

protected void Application_Error()
{
    HttpContext httpContext = HttpContext.Current;
    var exception=Server.GetLastError();
    var httpException = exception as HttpException ?? new HttpException(500, "Internal Server Error", exception);
    var jsonResponse = new
    {
        Message = exception.Message,
        StatusCode = httpException.GetHttpCode(),
        StackTrace=httpException.StackTrace
    };
    httpContext.Response.ContentType = "application/json";
    httpContext.Response.ContentEncoding = Encoding.UTF8;
    httpContext.Response.Write(JsonConvert.SerializeObject(jsonResponse));
    httpContext.Response.End();
}

enter image description here

Note: You could also redirect to a specific error page.

Moreover, you could leverage the customErrors in web.config and catch the error page for the specific HTTP error code. Also, you could check the HTTP status code under the Application_EndRequest event and write your custom response, details you could refer to this similar issue. Additionally, I would recommend you follow Demystifying ASP.NET MVC 5 Error Pages and Error Logging for more details about error handling.