获取登录用户ASP.NET MVC的用户名

时间:2016-09-13 14:50:29

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

我想获取登录用户名和域名的用户名。 获取它的代码在控制器中:

User.Identity.GetUserId()

在我的web.config中是:

<system.web>
    <identity impersonate="false"/>
    <authentication mode="Windows" />
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime />
    <pages controlRenderingCompatibilityVersion="4.0" />
</system.web>

目前,我只获得一个空字符串。我必须更改以获取Windows用户名信息?

其他人的旁注: 在我的研究中,我也得到了以下内容:

Environment.UserDomainName +  @"\" + Environment.UserName

在引用this时,它只传递线程正在运行的身份而不是窗口信息。

EDIT1:我目前正在调试模式下测试我的程序。

2 个答案:

答案 0 :(得分:2)

试试这个

HttpContext.User.Identity.Name

还要确保在web.config中的system.web中有授权标记

<authorization>
  <allow users="?" />
</authorization>

并在IIS中确保您将禁用匿名身份验证并启用与

相同的应用程序的窗口

enter image description here

答案 1 :(得分:0)

User.Identity.GetUserId()是来自Microsoft.AspNet.Identity的扩展方法。身份与Windows Auth不兼容(你必须使用其中一个),所以我不确定你在这里做了什么。

一般来说,在Windows Auth中,User.Identity.Name的值将采用{DOMAIN}\{USER}的形式。因此,如果您想要域名和/或用户名,则可以在\上拆分该字符串并获取您所追求的部分。

在身份方面,User.Identity.Name应该是ApplicationUser.UserName的值,但根据设置,它可能是ApplicationUser.Email