ASP.NET Request.UserHostName不包含主机名

5 asp.net c#-4.0

如果创建了新的数据集,我需要将请求计算机的主机名存储在数据库中.为了向用户清楚地指出这一点(它是所有公司内部的),我们将其显示为用户填写的表格中的三个文本框.这三个文本框就像这样填充:

protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            txtHostname.Text = Request.UserHostName.ToString();
            txtIPAdress.Text = Request.UserHostAddress.ToString();
            txtWindowsLogin.Text = Request.LogonUserIdentity.Name.ToString();
        }
    }
Run Code Online (Sandbox Code Playgroud)

但无论我测试的是哪个客户端,反向查找应该在Request.UserHostname中给出主机名的IP都不起作用,因此该字段填充了IP地址.如果我在服务器上使用nslookup,则反转工作正常.我可以从哪里得到任何提示?非常感谢.

Hac*_*ese 4

您需要配置 IIS才能使其正常工作。或者,如果您只在一处需要,您可以使用Dns.GetHostEntry进行反向查找。

每个请求的反向查找都会对性能产生严重影响,这就是默认情况下不启用它的原因。Dns.GetHostEntry如果可以的话我会推荐这条路线。

这是我们使用的一种有用的反向查找方法:

public static string ReverseLookup(string ip)
{
    if (string.IsNullOrEmpty(ip)) return ip;

     try 
     {
       return Dns.GetHostEntry(ip).Select(entry => entry.HostName).FirstOrDefault() ?? ip;
     } 
     catch(SocketException) { return ip; }
}
Run Code Online (Sandbox Code Playgroud)