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

问题描述

这里我可以使用这两种方法中的任何一种.有什么区别,我应该使用哪一种?

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

方法一:

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

    }

方法二:

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

    }

推荐答案

简短回答: 两者是相同的.

长答案:要确定两者之间的区别,请使用 Reflector(或您喜欢的任何反汇编程序).

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

HttpRequest.UserHostAddress 属性的代码如下:

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

注意它返回_wr.GetRemoteAddress()._wr 变量是 HttpWorkerRequest 对象的一个​​实例.有从 HttpWorkerRequest 派生的不同类,使用哪一个取决于您使用的是 IIS 6、IIS 7 还是更高版本,以及其他一些因素,但是您将在 Web 中使用的所有类应用程序对 GetRemoteAddress() 具有相同的代码,即:

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");
}

如您所见,GetRemoteAddress() 仅返回服务器变量 REMOTE_ADDR.

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

至于使用哪个,我建议使用 UserHostAddress 属性,因为它不依赖于魔法字符串".

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

快乐编程

这篇关于Request.UserHostAddress 和 Request.ServerVariables[“REMOTE_ADDR"].ToString() 有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 19:56