This SO answer presents an elegant solution to handling 404 errors. I modified the code given in that answer to also handle 400 errors (the response that happens when someone feeds a "potentially dangerous" character my website). My code looks like this:
/// <summary> Handle "page not found" (HTTP 404) and "dangerous/invalid syntax" (HTTP 400) errors. </summary>
protected void Application_EndRequest()
{
// This code is adapted from: https://stackoverflow.com/a/9026941/1637105
var code = Context.Response.StatusCode;
if (code == 404 || code == 400) {
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));
}
}
My problem is that if I have glimpse installed then, when I get a 400 error (for example, if I navigate to http://example.com/HiBob:), I get:
An exception of type 'System.NullReferenceException' occurred in Glimpse.Core.dll
Since glimpse doesn't seem to have any problem with the 404 errors that get rerouted through this code, I assume that glimpse is choking on the request path.
Is there something I can do in this code to URL-encode the request path before I send the new request off to be executed by the MVC pipeline?
EDIT: I updated the glimpse NuGet package to the latest version and the problem seems to be gone. Life is good. I'm an idiot (for not making sure I have the latest stuff before complaining that it doesn't work).