2010-03-28 18 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