C# Request.UserHostAddress 和 Request.ServerVariables["REMOTE_ADDR"].ToString() 有什么区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13994582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the difference between Request.UserHostAddress and Request.ServerVariables["REMOTE_ADDR"].ToString()
提问by MonsterMMORPG
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
{
}
采纳答案by Scott Mitchell
Short answer:The two are identical.
简短回答:两者是相同的。
Long answer:To determine the difference between the two use Reflector (or whatever disassembler you prefer).
长答案:要确定两者之间的区别,请使用 Reflector(或您喜欢的任何反汇编程序)。
The code for the HttpRequest.UserHostAddress
property follows:
HttpRequest.UserHostAddress
属性代码如下:
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:
请注意,它返回_wr.GetRemoteAddress()
. 该_wr
变量是一个实例HttpWorkerRequest
对象。派生自不同的类HttpWorkerRequest
以及使用哪一个取决于您使用的是 IIS 6、IIS 7 还是更高版本,以及其他一些因素,但是您将在 Web 应用程序中使用的所有类都具有相同的代码GetRemoteAddress()
,即:
public override string GetRemoteAddress()
{
return this.GetServerVariable("REMOTE_ADDR");
}
As you can see, GetRemoteAddress()
simply returns the server variable REMOTE_ADDR
.
如您所见,GetRemoteAddress()
只需返回服务器变量REMOTE_ADDR
。
As far as which one to use, I'd suggest the UserHostAddress
property since is doesn't rely on "magic strings."
至于使用哪个,我建议使用该UserHostAddress
属性,因为它不依赖于“魔法字符串”。
Happy Programming
快乐编程
回答by Mike Brind
There is no difference. They return exactly the same value. However, one is IntelliSense-friendly whereas the other is not.
没有区别。它们返回完全相同的值。但是,一种是 IntelliSense 友好的,而另一种则不是。