Error loading HttpRequestBase.UserHostAddress

I collect some of the information about users who visit a specific section of my site, and I get a strange error. I have a section of code that does the following.

string userIp = request.UserHostAddress; 

The request variable is HttpRequestBase. This works very well from time to time, and I get an IP - in other cases it causes an error, and I'm not sure how to protect it. This is from my error log.

"The value is not in the expected range. In System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal (Int32 errorCode, IntPtr errorInfo) in System.Web.Hosting.IIS7WorkerRequest.GetServerVariableInternal (String name)"

It seems that the first time I go to the page, it works fine, the error occurs if I refresh, or quickly go to another page that captures the same variable.

+7
source share
1 answer

I had this exact problem with my registrar. I believe that I am using dependency injection.

In my case, I was getting this error because I did not bind my registrar to the request area. Thus, he lived between requests and supported some of the HttpContext properties, but threw exceptions on those who spoke with IIS.

Since I'm using Ninject, it's just a matter of adding the InRequestScope() method from the Ninject.Web.Common namespace to my binding.

In short : this exception seems to be HttpContext for an obsolete HttpContext instance when it is accessed by certain properties that have been redirected to IIS and for which the request is no longer valid.

Hope this helps!

ps NLog is better than any logger you write. Or, if you just want exceptions, head over to ELMAH.

+6
source

All Articles