From time to time, my Web tests were throwing a "400 Bad Request" response. It was always a problem with the Ivonna setup, but the request itself was a little bit too laconic: it said "Bad request" inside a body tag, and that was it: no exception message, no stack trace, nothing!
Turned out that if the runtime fails to create an instance of HttpContext, it swallows the exception and just sends a hardcoded response. Just take a look at this:
try {
context = new HttpContext(wr, false);
}
catch {
wr.SendStatus(400, "Bad Request");
wr.SendKnownResponseHeader
(12, "text/html; charset=utf-8");
byte[] bytes = Encoding.ASCII.GetBytes
("<html><body>Bad Request</body></html>");
wr.SendResponseFromMemory(bytes, bytes.Length);
wr.FlushResponse(true);
wr.EndOfRequest();
return;
}
In order to figure out what's going on, I had to create the Context manually. Turned out that the exception is thrown inside my code, and the actual cause is that the hosting environment is not initialized in the current AppDomain. So, I just added a simple check (fortunately there's a public property, HostingEnvironment.IsHosted), and hopefully we can forget about the Evil Request Mystery.
I thought it's worth a new version, you can get it here, as always.