我在 Silverlight 中使用 ASP.NET (.asmx) Web 服务。由于在Silverlight中找不到客户端IP地址,只好在服务端记录这个。
这些是我尝试过的一些方法:
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()
最佳答案
您应该尝试找出 NullReferenceException
的确切位置。来自。更改您的代码以了解某些内容可以返回 null。例如,在
HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]
HttpContext.Current
可能返回 null,或者 .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();
}
}
附言我不知道你为什么要使用
GetValue(0)
.使用 hostAddresses[0]
反而。
关于asp.net - ASP.NET (.asmx) Web 服务中的客户端 IP 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2534261/