使用IIS获取客户端名称/ IP

时间:2018-12-13 00:17:43

标签: c# asp.net-mvc iis

如何捕获用户详细信息,例如用户身份或IP。当前,我正在使用c#mvc,我当前的项目运行良好,并且只能在本地项目的调试模式下运行时捕获用户名和ip,但是如果我要将其发布到服务器IIS,则每个客户端都将获得服务器信息而不是其身份。

这是我当前的简单流程:

在我的视图中,我要显示用户名:

<html>
<body>
<a id="test" class="navbar-brand" href="#" style="float:right">User</a>
<html>
</body>

<script>
    $(document).ready(function () {

        $.ajax({
            url: '/Home/getUserInfo',
            type: 'GET',
            dataType: 'json',
            success: function (data) {
                document.getElementById("test").innerHTML = data;
            },
            error: function (jqXhr, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });
    });
</script>

在我的控制器上,我具有以下功能:

public ActionResult getUserInfo()
        {            
            System.Security.Principal.WindowsIdentity user = System.Security.Principal.WindowsIdentity.GetCurrent();

            string name = user.Name;
            return Json(name, JsonRequestBehavior.AllowGet);
        }

任何建议/评论TIA。

1 个答案:

答案 0 :(得分:0)

这仅在用户已登录您的应用程序时有效

public ActionResult GetUserInfo()
{
    string ip = HttpContext.Request.UserHostAddress;
    string name = HttpContext.Request.RequestContext.HttpContext.User.Identity.Name;
    return Json(new { name = name, ip = ip }, JsonRequestBehavior.AllowGet);
}

如果这对您不起作用,我认为这里有一些解决方案>> Getting the name of the current Windows user returning "IIS APPPOOL/Sitename"