如何在c#和asp.net中获取客户端主机名,本地计算机名和用户名

las*_*mos 3 c# asp.net

我有IP地址,但由于某种原因,我可以正确解析名称以显示本地计算机名称.我尝试了几件事,所有这些都显示服务器主机名?

    ipadd = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
    IPAddress myIP = IPAddress.Parse(ipadd);
    IPHostEntry GetIPHost = Dns.GetHostEntry(myIP);


    //userhostname = System.Environment.MachineName;
    //userhostname = Dns.GetHostName(); //Resolve ServerHostName not computer
    //userhostname = HttpContext.Current.Request.UserHostName;
    //userhostname = HttpContext.Current.Request.UserAgent;
    userhostname = GetIPHost.HostName;
Run Code Online (Sandbox Code Playgroud)

对于用户名,我要使用

nametext = WindowsIdentity.GetCurrent().Name;
//Shows server name when deployed on server 
//when debuging and running localy shows correctly current user logged in

//nametext = HttpContext.Current.Request.ServerVariables["LOGON_USER"]; 
// not returning anything
Run Code Online (Sandbox Code Playgroud)

我切换了身份验证,没有结果

<authentication mode="Forms">
<authentication mode="Windows">
Run Code Online (Sandbox Code Playgroud)

jru*_*ell 6

使用HttpRequest.UserHostAddressHttpRequest.UserHostName用于客户端IP和计算机名称.

假设您已正确配置身份验证,则可以从中获取客户端用户IIdentity.Name.

在的情况下Page,你可以使用Request.UserHostAddress,Request.UserHostNameUser.Identity.Name.

  • 由于没有用户,您无法使用匿名身份验证获取用户名. (2认同)
  • 不,我不知道从javascript获取用户名的方法(没有使用服务器端代码访问`User.Identity.Name`的ajax).请参阅[通过浏览器获取已登录用户的用户名](http://stackoverflow.com/questions/5271742/get-username-of-logged-in-user-in-os-via-browser). (2认同)