如何使用.net Framework4.0获取MVC4中的当前Windows用户登录名

时间:2016-08-26 13:16:54

标签: asp.net-mvc asp.net-mvc-4 authentication

我一直在尝试获取当前的Windows用户名,但最后没有。 以下是我尝试但无法获取用户名的方式,我得到空值

  1. STEP我尝试过

    string usr System.Web.HttpContext.Current.User.Identity.Name;
    

    得到空值

  2. STEP在我的本地ISS中检查安全和启用Windows身份验证

  3. 我的项目中的STEP我已选中单选按钮以使用“使用Visual Studio”开发服务器

  4. 在我的web.config文件中选择Form = Windows

    <authentication mode="Windows">
        <forms loginUrl="~/Account/Login" timeout="2880" />
    </authentication>
    
  5. STEP:我也尝试过授权

    <authentication mode="Windows" >
        <forms loginUrl="~/Account/Login" timeout="2880" />
    </authentication>
    <authorization>
        <deny users="?"/>
    </authorization>
    
  6. STEP:我在我的开发服务器中托管并检查了匿名身份验证=禁用和Windows身份验证=启用

  7. STEP:授权(我在控制器上使用过它)

    string str = System.Web.HttpContext.Current.User.Identity.Name 
    

    但得到空值

  8. 我已经尝试了所有这些方法来获取当前用户名但是获得空值。我试图让它在控制器下。有没有办法得到这个?请指教。

1 个答案:

答案 0 :(得分:5)

web.config

中设置此项
<configuration>
    ....
    <system.web>
    <authentication mode="Windows" />
        ....
    </system.web>
</configuration>        

这使 Windows身份验证能够获取您的Windows用户名。

接下来,如果您使用的是Internet Explorer,则需要添加&#34; http://localhost&#34;到有效的 Intranet 网站列表(在IE Internet Options > Security > Local Intranet > Sites > Advanced中,然后将http://localhost添加到该列表中)。这允许IE自动获取当前Windows用户并启动您的网站,而无需再次提示用户名/密码。

使用HomeController Index方法:

public ActionResult Index()
{
    // get the currently logged on Windows user
    ViewBag.UserName = HttpContext.User.Identity.Name;
    return View();
}

然后在你看来:

<h3>Hello, @ViewBag.UserName !</h3>

那就是它!