I need to have Elmah log potentially dangerous Request.Form values caught by HttpRequestValidationException.
This is part of my ongoing Elmah improvements listed here
This is a known Elmah issue, and there seems to be no official solution included in the nugget package. There are various workarounds, a lot of which involve editing the Elmah source code. I found one that works for MVC applications that was actually quite simple, once I worked out what I actually needed to do!
So I need Elmah to log this sort of stuff.
What looked like the easiest way to do this was to create a new exception filter, register it with the global filters, and use it to manually throw an exception of this type to Elmah.
I found a blog post from way back detailing how to do this here
And it didn’t work… After puzzling over it for a while I realised what I was doing wrong. The example shows the RegisterGlobalFilters as part of the Global.asax.cs file. It’s actually in the FilterConfig.cs file. I think this post from 2012 shows the way Visual Studio USED to set up an MVC project. I’ve actually been caught out by this before when trying to add to the RegisterRoutes method. I should have realised what was going on sooner, but I guess I was tired yesterday… This morning when trying to work out why my new exception filter was not being hit, I saw that there already was a RegisterGlobalFilters method being called above where I was trying to do mine.
My Global.asax.cs looks like this
I added this code to the FilterConfig.cs
And this is the new exception filter
I stored it as a class in a new Filters folder. In the future there may be more custom filters, and this is how the demo project is structured in the ASP.NET MVC 4 Custom Action Filters tutorial, so it seemed like a good way to go.
Throwing a bit of dodgy code into one of my text boxes sent me to the custom error screen, and the following appeared in the Elmah log:
|500||HttpRequestValidation||A potentially dangerous Request.Form value was detected from the client (Field_Name="bad code here").|
These errors are now being logged, but not getting emailed. That’s a problem for the next post, however…