I am capturing some of the information on users that visit a particular section of my website and I am getting an odd error. I have a section of code that does the following.
string userIp = request.UserHostAddress;
The request variable is a HttpRequestBase. At times this works just fine and I get the IP - other times it throws an error that I am not sure how to safeguard against. This is from my error log.
"Value does not fall within the expected range. at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo) at System.Web.Hosting.IIS7WorkerRequest.GetServerVariableInternal(String name)"
It seems that the first time I go to a page it works just fine, the error gets thrown if I do a refresh, or go quickly to another page that capturs the same variable.
I had this exact issue with my logger. I'm using dependency injection, as I suspect you are.
In my case, I was getting this error because I wasn't binding my logger to the request scope. So, it was living between requests and maintaining some of the HttpContext
properties but throwing exceptions on the ones talking to IIS.
Since I'm using Ninject, this was simply a matter of adding the InRequestScope()
method, from the Ninject.Web.Common
namespace, to my binding.
In short: this exception seems to be thrown for a stale instance of HttpContext
when certain properties, that are marshalled to IIS and for which the request is no longer valid, are accessed.
Hope that helps!
p.s. NLog is better than any logger you'll write. Or, if you just want exceptions, drop in ELMAH.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With