.NET : How to make ELMAH log HttpRequestValidationException Error

Last updated: May 15, 2017

ELMAH (Error Logging Modules and Handlers) is an open source error logging framework for ASP.NET and for ASP.NET MVC. When added to the web application, exceptions that are thrown will trigger event handlers in the ELMAH that will log nearly all unhandled exceptions, but using ASP.NET 4 there is one Exception type that the ELMAH v1.2 is unable to log and that is HttpRequestValidationException.

In this article you will learn three ways to make ELMAH log this specific exception.

This exception is thrown when input string that contains anything resembling HTML or JavaScript is received from the client as part of the request data. This happens even in case of harmless HTML code like <b>, <br/>.

When HttpRequestValidationException is thrown, we get Yellow Screen of Death with the following information:

A potentially dangerous Request.Form value was detected from the client (...).

Description: Request Validation has detected a potentially dangerous client input value, and processing of the request has been aborted. This value may indicate an attempt to compromise the security of your application, such as a cross-site scripting attack. To allow pages to override application request validation settings, set the requestValidationMode attribute in the httpRuntime configuration section to requestValidationMode="2.0"...

Exception Details: System.Web.HttpRequestValidationException:
A potentially dangerous Request.Form value was detected from the client(...).

Parentheses  will contain the XML tags that caused the Exception.

We can fix this problem using three different ways:

  • Modify web.config

    Simplest solution is to add the following line under <system.web> section in the web.config file :

    <httpRuntime requestValidationMode="2.0" />

    In ASP.NET 4, request validation is enabled for all requests but in previous versions it applied only to ASP.NET pages (.aspx files).
    As the description in Yellow Screen of Death already says, we can set ASP.NET 4 to revert back to old behavior.

    If you use this solution, it is recommended that you explicitly check all the inputs yourself for potential XSS attacks.

    For more information about Request Validation in ASP.NET check the MSDN.

    Next two solutions solve ELMAH problem without reverting back to old behavior.

  • Add Custom Filter to the Global Filter Collection - ASP.NET MVC only

    Using ASP.NET MVC 3, you can log exceptions before ELMAH "swallows" the error by adding custom exception filter to the global filter collection. Global filters run for every action of every controller. Our custom filter will manually log Request Validation Exception when it occurs.
    We add this exception filter to the collection in RegisterGlobalFilters method of Global.asax file.

    May 2017 Update

    For ASP.NET MVC 4 and newer

    Since MVC 4, the registration of global filters is specified in App_Start/FilterConfig.cs.

    As this article is from 2012, you also might want to check this blog post from 2017 written by commentator Kellamity.

    First let's create this custom filter:

    public class ElmahRequestValidationErrorFilter : IExceptionFilter
    {
        public void OnException(ExceptionContext context)
        {
            if (context.Exception is HttpRequestValidationException)
               Elmah.ErrorLog.GetDefault(HttpContext.Current).Log(new Error(context.Exception));
        }
    }
    

    Next step is to add custom filter to the global filter collection. Open global.asax file and find RegisterGlobalFilters method. Next we add our filter before HandleErrorAttribute is added as shown below:

    public static void RegisterGlobalFilters (GlobalFilterCollection filters)
    {
    
        //custom filter is added first
        filters.Add(new ElmahRequestValidationErrorFilter());
    
        filters.Add(new HandleErrorAttribute());
    
    }

    The reason we register custom filter before HandleErrorAttribute is that OnException(ExceptionContext) filters run in reverse order so the HandleErrorAttribute will run first.

    With this solution ELMAH will now log the Request Validation Exceptions but the detailed page of the log will only contain Stack Trace while Server Variables will be missing.

    NOTE: In ASP.NET MVC 3 you can fix HttpRequestValidationException error by decorating the controller or method with [ValidateInput(false)] attribute.

    In this case Request Validation Exception will not be thrown but if the code throws some other exception, that exception will not get logged by ELMAH.

  • Modifying ELMAH Source Code

    This solution requires you to modify ELMAH source code.

    You do so by doing the following:

    1. Download ELMAH source code.
    2. Extract the zip file and load the solution Elmah.sln in Visual Studio. Solution file is located at src\Solutions\2010
    3. Open Error.cs file and locate end of public Error(Exception e, HttpContext context) constructor.
    4. There you should find the following code:
      _queryString = CopyCollection(request.QueryString);
      _form = CopyCollection(request.Form);
      _cookies = CopyCollection(request.Cookies);
    5. Change that code to this:
      try
      {
          _queryString = CopyCollection(request.QueryString);
          _form = CopyCollection(request.Form);
          _cookies = CopyCollection(request.Cookies);
      }
      catch (HttpRequestValidationException ex)
      {
          Trace.WriteLine(ex);
      }
      
    6. Rebuild the solution.
    7. In your project that uses ELMAH, remove old Elmah.dll from references.
    8. Add a reference to the new modified Elmah.dll file.

That last solution is the most effective one but it does require you to be comfortable with modifying code on Open Source Projects.

Thanks to davidduffett for the third solution.

if you find this article useful, please drop a comment or consider sharing either the article or the blog using the social icons.

Share this page

2 Comments

Add a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back to Top