2010-03-28 19 views
7

我在Silverlight中使用ASP.NET(.asmx)Web服务。由于无法在Silverlight中查找客户端IP地址,因此我必须在服务端记录此信息。 这些都是一些方法我都试过:ASP.NET中的客户端IP地址(.asmx)webservices

Request.ServerVariables("REMOTE_HOST") 
HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] 
HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; 
Request.UserHostAddress() 
Request.UserHostName() 
string strHostName = Dns.GetHostName(); 
string clientIPAddress = Dns.GetHostAddresses(strHostName).GetValue(0).ToString(); 

上述所有方法我的本地系统上正常工作,但是当我发布一个生产服务器上我的服务,它开始给错误,

Error: Object reference not set to an instance of an object. StackTrace:

at System.Web.Hosting.ISAPIWorkerRequestInProc.GetAdditionalServerVar(Int32 index)

at System.Web.Hosting.ISAPIWorkerRequestInProc.GetServerVariable(String name)

at System.Web.Hosting.ISAPIWorkerRequest.GetRemoteAddress()

at System.Web.HttpRequest.get_UserHostAddress()

回答

2

如果您需要使用反射在System.Web.Hosting.ISAPIWorkerRequestInProc.GetAdditionalServerVar代码一看,这就是我们看到:

private string GetAdditionalServerVar(int index) 
{ 
    if (this._additionalServerVars == null) 
    { 
     this.GetAdditionalServerVariables(); 
    } 
    return this._additionalServerVars[index - 12]; 
} 

我看到两个原因,这可能引发一个NullReferenceException:

1)_additionalServerVars成员存在多线程问题。我不认为这可能发生,因为A)我不明白为什么在测试期间服务器上会有很大的负载,并且B)ISAPIWorkerRequestInProc实例可能与一个线程有关。 2)你的服务器不是最新的,生产中的代码与我在我的机器上看到的不一样。

所以我会做的是检查服务器,确保它是最新的.NET框架DLL。当我尝试Request.UserHostAddress 发生

5

您应该尝试找出NullReferenceException来自哪里。改变你的代码来理解某些东西可以返回null。例如,在

HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] 

HttpContext.Current可以retrun空,或.Request可以返回null,或.ServerVariables["REMOTE_ADDR"]可以返回null。此外,在

string clientIPAddress = System.Net.Dns.GetHostAddresses(strHostName).GetValue(0).ToString(); 

GetHostAddresses(strHostName)可以返回null或.GetValue(0)可以返回null。

如果某个方法或属性可能返回null,则应在取消引用它之前检查是否为null。例如,

IPAddress[] hostAddresses = System.Net.Dns.GetHostAddresses(strHostName); 
string clientIPAddress; 
if (hostAddresses != null) 
{ 
    object value = hostAddresses.GetValue(0); 
    if (value != null) 
    { 
     clientIPAddress = value.ToString(); 
    } 
} 

P.S.我不知道你为什么要使用GetValue(0)。改为使用hostAddresses[0]

+0

空引用异常或HttpContext.Current.Request.ServerVariables [“REMOTE_ADDR”] 我只是不能找出任何方式获取客户端IP在我的ASMX服务。 =( – 2010-03-29 19:52:04

+0

@ Zain:就像我说的,在使用任何这些值之前检查null。实际上,在尝试'HttpContext.Current.Request'之前,一定要测试'HttpContext.Current'来查看它是否为null。 – 2010-03-29 20:50:31