代码之家  ›  专栏  ›  技术社区  ›  JoshBerke

获取远程地址的空引用

  •  3
  • JoshBerke  · 技术社区  · 16 年前

    我有一个ASMXWeb服务在IIS7下以经典模式运行。此服务具有以下代码:

       try
       {
           env.ExternalIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
       }
       catch (Exception ex)
       {
    
           LogWriter.WriteError(ex);
           env.ExternalIP="000.000.000.000";
       } 
    

    这将导致以下堆栈跟踪。我只是在这里修改了usercode调用堆栈的名称来保护无辜者:

    Message: An Exception of type: NullReferenceException occured in method:  GetAdditionalServerVar
    ExceptionMsg: Object reference not set to an instance of an object.
    ===Stack Trace===
       at System.Web.Hosting.ISAPIWorkerRequestInProc.GetAdditionalServerVar(Int32 index)
       at System.Web.Hosting.ISAPIWorkerRequestInProc.GetServerVariable(String name)
       at System.Web.HttpRequest.AddServerVariableToCollection(String name)
       at System.Web.HttpRequest.FillInServerVariablesCollection()
       at System.Web.HttpServerVarsCollection.Populate()
       at System.Web.HttpServerVarsCollection.Get(String name)
       at System.Collections.Specialized.NameValueCollection.get_Item(String name)
       at MyService.MyMethod() 
    

    我在这里不知所措,因为这是非常基本的普通代码。

    编辑

    这就更奇怪了。我添加了一些基本的代码,只是想知道我现在可以得到什么服务器变量。当我尝试获取所有密钥时,出现相同的异常:

    引用未设置为 对象。在 索引)在 名称)在 名称)在 System.Web.HttpRequest.FillInServerVariablesCollection() 在 System.Web.httpservervarscolection.get\u AllKeys() 在MyService.MyHelper()

    当我在看框架代码时,当缓存服务器变量的数组没有填充时,可能会发生这种情况,当有一个指向某个上下文的空指针时,可能会发生这种情况……这似乎是框架代码的一个相当核心的部分。

    3 回复  |  直到 16 年前
        1
  •  1
  •   JoshBerke    13 年前

    回顾我的老问题。我相信这是由.net或IIS中的错误引起的。实际上,web服务被标记为单向的。通过这样做,用户在处理程序执行之前就断开了连接,因此除非您在处理程序执行之前设法访问请求变量,否则您将遇到空引用异常。

    解决方法是添加一个HTTP模块,该模块在向客户机发送响应并执行处理程序之前访问管道中的属性。

        2
  •  0
  •   Klaus Byskov Pedersen    16 年前
    推荐文章