是什么Request.UserHostAddress和Request.ServerVariables [" REMOTE_ADDR&QUOT]之间的差。的ToString() [英] What is the difference between Request.UserHostAddress and Request.ServerVariables["REMOTE_ADDR"].ToString()

查看:648
本文介绍了是什么Request.UserHostAddress和Request.ServerVariables [" REMOTE_ADDR&QUOT]之间的差。的ToString()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里,我可以使用的这2种方法。有什么区别,我应该使用哪一个?

方法1:

 字符串srUserIp =;
    尝试
    {
        srUserIp = HttpContext.Current.Request.ServerVariables [REMOTE_ADDR]的ToString()。
    }
    抓住
    {    }

方法2:

 字符串srUserIp =;
    尝试
    {
        srUserIp = Request.UserHostAddress.ToString();
    }
    抓住
    {    }


解决方案

简短的回答:这两个是相同的。

龙答::要确定两个使用反射镜(或任何反汇编您preFER)之间的差值

在code为的Htt prequest.UserHostAddress 属性如下:

 公共字符串UserHostAddress
{
    得到
    {
        如果(this._wr!= NULL)
        {
            返回this._wr.GetRemoteAddress();
        }
        返回null;
    }
}

请注意,它返回 _wr.GetRemoteAddress()。在 _wr 变量是的HttpWorkerRequest 对象的实例。有从的HttpWorkerRequest 派生不同类别和一个用来取决于您使用的是IIS 6,IIS 7或超越,和其他一些因素的影响,但所有的人你将使用Web应用程序具有相同的code为 GetRemoteAddress(),即:

 公众覆盖字符串GetRemoteAddress()
{
    返回this.GetServerVariable(REMOTE_ADDR);
}

正如你所看到的, GetRemoteAddress()直接返回服务器变量 REMOTE_ADDR

至于用哪一个,我建议在 UserHostAddress 财产既然是不依赖于神奇的字符串。

快乐编程

Here I can use either of these 2 methods. What are the differences and which one should I use?

Method 1:

    string srUserIp = "";
    try
    {
        srUserIp = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
    }
    catch
    {

    }

Method 2:

    string srUserIp = "";
    try
    {
        srUserIp = Request.UserHostAddress.ToString();
    }
    catch
    {

    }

解决方案

Short answer: The two are identical.

Long answer: To determine the difference between the two use Reflector (or whatever disassembler you prefer).

The code for the HttpRequest.UserHostAddress property follows:

public string UserHostAddress
{
    get
    {
        if (this._wr != null)
        {
            return this._wr.GetRemoteAddress();
        }
        return null;
    }
}

Note that it returns _wr.GetRemoteAddress(). The _wr variable is an instance of an HttpWorkerRequest object. There are different classes derived from HttpWorkerRequest and which one is used depends on whether you are using IIS 6, IIS 7 or beyond, and some other factors, but all of the ones you would be using in a web application have the same code for GetRemoteAddress(), namely:

public override string GetRemoteAddress()
{
    return this.GetServerVariable("REMOTE_ADDR");
}

As you can see, GetRemoteAddress() simply returns the server variable REMOTE_ADDR.

As far as which one to use, I'd suggest the UserHostAddress property since is doesn't rely on "magic strings."

Happy Programming

这篇关于是什么Request.UserHostAddress和Request.ServerVariables [" REMOTE_ADDR&QUOT]之间的差。的ToString()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆