If my site receives a GET request for a URL with "potentially dangerous" characters, e.g.:
http://example.com/unsafe:)
then the user gets a response that looks like the server had an error (specifically, the server choked on the "A potentially dangerous Request.Path value was detected from the client" HttpException
). And, worse, the user doesn't get my custom error page (Views/Shared/Error.cshtml) because the global HandleErrorAttribute doesn't see this particular "error". So the user gets the generic "something is broken but I won't tell you what it is, nya nya nya!" page.
I want to change this response so that the user gets something that looks like my site's 404 page ("can't find the page you're asking for"), but with an HTTP 400 response code.
As near as I can tell, the only place to try to handle this particular exception is in the Global.asax Application_Error routine. (My custom global HandleErrorAttribute doesn't see the exception.)
Any help or guidance (or a sharp slap on the wrist for trying to do something I shouldn't be trying to do) would be appreciated!
FYI, here is my existing Global.asax code:
/// <summary> Handle "page not found" (HTTP 404) errors. </summary>
protected void Application_EndRequest()
{
// This code is from: http://stackoverflow.com/a/9026941/1637105
if (Context.Response.StatusCode == 404) {
Response.Clear();
var rd = new RouteData();
rd.DataTokens["area"] = "AreaName"; // In case controller is in another area
rd.Values["controller"] = "Errors";
rd.Values["action"] = "NotFound";
IController c = new ErrorsController();
c.Execute(new RequestContext(new HttpContextWrapper(Context), rd));
}
}
protected void Application_Error(object sender, EventArgs e)
{
// Convert "A potentially dangerous Request.Path value was detected from the client" to an HTTP 404 (page not found) response
var ex = Server.GetLastError();
if (ex != null && ex is HttpException) {
var re = new Regex(@"(?ix: \b potentially \b.+?\b dangerous \b.+?\b value \b.+?\b detected \b.+?\b client \b )");
if (re.IsMatch(ex.Message)) {
// <Convert the response to 404>
}
}
}
EDIT:
I should add that I have elmah wired up and happy, so I get emails several times a week when the bad guys ping my site with
/w00tw00t.at.blackhats.romanian.anti-sec:)
This whole exercise came about when I decided to suppress the elmah emails, and I discovered that more benign requests that happen to contain "dangerous" characters result in the user getting a really ugly web page that looks like my website is broken.
Suppressing the elmah email is easy. I guess I'm asking if I'm going about this the right way by detecting the error in the Application_Error routine, and, if so, what is a reasonably proper thing to do about in that routine.