HttpRequestBase.UserHostAddress 抛出错误
我正在捕获有关访问我网站特定部分的用户的一些信息,但出现了一个奇怪的错误。我有一段代码执行以下操作。
string userIp = request.UserHostAddress;
请求变量是 HttpRequestBase。有时这工作得很好,我得到了 IP - 其他时候它会抛出一个错误,我不知道如何防范。这是来自我的错误日志。
“值未落在预期范围内。在 System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo) at System.Web.Hosting.IIS7WorkerRequest.GetServerVariableInternal(String name)"
似乎我第一次进入一个页面时效果很好,如果我刷新或快速转到另一个捕获该页面的页面,则会抛出错误相同的变量。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我的记录器遇到了这个问题。我正在使用依赖注入,我怀疑你也是如此。
就我而言,我收到此错误是因为我没有将记录器绑定到请求范围。因此,它处于请求之间并维护一些
HttpContext
属性,但在与 IIS 通信的属性上抛出异常。由于我使用的是 Ninject,因此只需将
InRequestScope()
方法从Ninject.Web.Common
命名空间添加到我的绑定即可。简而言之:当访问编组到 IIS 且请求不再有效的某些属性时,
HttpContext
的过时实例似乎会引发此异常。希望有帮助!
ps NLog 比您编写的任何记录器都要好。或者,如果您只是想要例外,请加入 ELMAH。
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 theNinject.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.