我一直在尝试获取当前的Windows用户名,但最后没有。 以下是我尝试但无法获取用户名的方式,我得到空值
STEP我尝试过
string usr System.Web.HttpContext.Current.User.Identity.Name;
得到空值
STEP在我的本地ISS中检查安全和启用Windows身份验证
我的项目中的STEP我已选中单选按钮以使用“使用Visual Studio”开发服务器
在我的web.config
文件中选择Form = Windows
<authentication mode="Windows">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
STEP:我也尝试过授权
<authentication mode="Windows" >
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
<authorization>
<deny users="?"/>
</authorization>
STEP:我在我的开发服务器中托管并检查了匿名身份验证=禁用和Windows身份验证=启用
STEP:授权(我在控制器上使用过它)
string str = System.Web.HttpContext.Current.User.Identity.Name
但得到空值
我已经尝试了所有这些方法来获取当前用户名但是获得空值。我试图让它在控制器下。有没有办法得到这个?请指教。
答案 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>
那就是它!