asp.net - ASP.NET (.asmx) Web 服务中的客户端 IP 地址

标签 asp.net web-services asmx

我在 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/

相关文章:

java - 如何在java中使用restful wcf服务?

.net - 是什么导致了这种情况下的瓶颈?

c# - Webservice复杂类型和类继承

c# - C#中如何合并日期和时间

javascript - 无法根据 Google Chrome 上第一个 <select> 中选择的值填充 <SELECT> 选项

rest - GraphQL 比 REST 好在哪里?

asp.net - 使用 jquery 调用 ascx 页面方法

c# - 支持 iOS Mobile Web - 陷入文件预览

c# - 请求的操作超时已过期

android - 使用证书或其他身份验证针对 Web 服务进行验证