C#get client ip address Request.ServerVariables [" HTTP_X_FORWARDED_FOR"]

时间:2018-04-25 10:33:46

标签: c#

我想在工具类中获取客户端IP地址,但在调用Request.ServerVariables["HTTP_X_FORWARDED_FOR"]时出错。错误消息是:

  

对象引用未设置为对象的实例

以下是代码:

    public static string GetIpAddress()
    {
        string _stringIpAddress = string.Empty;
        try
        {
            _stringIpAddress = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (_stringIpAddress == null)
            {
                _stringIpAddress = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }
        }           
        catch (Exception ex)
        {
            Logging.LogError(string.Concat("GetIpAddress()", ex.Message));
        }
        return _stringIpAddress;
    }

我该如何解决?

0 个答案:

没有答案