0

I am trying to prevent having this raw error appear on the screen when the user enters e.g. pointed brackets in an input field:

[System.Web.HttpRequestValidationException] A potentially dangerous Request.Form value was detected from the client (Message="

I've learned in posts like this one that I should be able to catch and handle this error in the void Application_Error(object sender, EventArgs e) method in the Global.asax.cs file, e.g. I have this code:

protected void Application_Error(object sender, EventArgs e)
{
    Exception ex = Server.GetLastError();

    if (ex is HttpRequestValidationException)
    {
        Response.Clear();
        Response.StatusCode = 200;
        Response.Write(@"<html><body>HTML is not allowed.</body></html>");
        Response.End();
    }
}

But regardless of what code I have in the void Application_Error(object sender, EventArgs e) method, code execution does not enter it, but rather simply outputs the raw error as before.

What could be preventing code execution from entering the void Application_Error(object sender, EventArgs e) method?

Note: I don't have custom errors set to RemoteOnly in my Web.config as seems to be the issue in Is global.asax Application_Error event not fired if custom errors are turned on?

Edward Tanguay
  • 189,012
  • 314
  • 712
  • 1,047
  • Have you tried adding a breakpoint to `Response.Clear();`? Is it getting hit? – mjwills Jun 25 '18 at 13:11
  • 1
    Possible duplicate of [Is global.asax Application\_Error event not fired if custom errors are turned on?](https://stackoverflow.com/questions/12111387/is-global-asax-application-error-event-not-fired-if-custom-errors-are-turned-on) – mjwills Jun 25 '18 at 13:16
  • If you have any other error handler (Filters or Middleware) check to see if they are not intercepting the error in the pipeline and clearing it before it reaches that handler. `Response.TrySkipIisCustomErrors = true;` – Nkosi Jun 25 '18 at 13:20
  • @mjwills, I have a breakpoint at `Exception ex = Server.GetLastError();` and it doesn't even get to that point. – Edward Tanguay Jun 25 '18 at 13:34
  • @mjwills, regarding the possible duplicate of https://stackoverflow.com/questions/12111387/is-global-asax-application-error-event-not-fired-if-custom-errors-are-turned-on, I don't have custom errors set to RemoteOnly in Web.config as seems to be the issue in that question. – Edward Tanguay Jun 25 '18 at 13:37
  • I can catch execution in `Global.asax.cs` in the method `Application_AuthenticateRequest` after the form post, but when I step through, it never enters `Application_Error`. – Edward Tanguay Jun 25 '18 at 13:55

0 Answers0