3

我想检查使用Windows身份验证的用户的登录名。 我有这个作为我的控制器的构造函数:MVC中的Windows身份验证

public class HomeController : BaseController 
{ 
    public string UserIdentityName; 

    public HomeController() 
    { 
     UserIdentityName = System.Web.HttpContext.Current.User.Identity.Name;// HttpContext.Current.User.Identity.Name; 
    } 
} 

但UserIdentityName返回空字符串...

我也有这个在我的web.config:

<authentication mode="Windows" /> 

什么想法?

回答

5

不要尝试访问控制器构造函数中的任何HttpContext相关的东西。您应该访问它的最早阶段是Initialize方法或在控制器操作中。

例如:

[Authorize] 
public ActionResult Index() 
{ 
    string user = User.Identity.Name; 
    ... 
} 

另外,还要确保你有你的Web服务器上启用Windows身份验证(NTLM)。

+0

我仍然得到空... –

+1

您可能尚未将您的Web服务器配置为需要Windows身份验证。 –

+0

Im使用Casini ... –

1

尝试增加:

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

拒绝匿名用户访问。

11

在解决方案资源管理器窗格中选择Web项目并按F4。 (不右键+属性,那是不同的)

在属性面板设置:
Windows身份验证:启用
匿名身份验证:残疾人

在web.config中:<authentication mode="Windows"></authentication>

要获取用户名:

HttpContext.Current.User.Identity.Name OR User.Identity.Name 

运行你的项目,快乐的日子!

+0

这似乎并没有在VS 2010 :( – 2013-02-05 21:32:58

+0

双重检查。我犯了这个错误 - 有两个设置顶部的匿名身份验证和项目属性底部的Windows身份验证我创建了一个虚拟的Intranet MVC应用程序并阅读要实现的readme.txt。 – Pete

2

Chaps,

如果您在IISExpress中运行。请确保以下设置如图:

在web.config中

<authentication mode="Windows"/> 
<authorization> 
    <deny users="?"/> 
</authorization> 

在记事本中打开projectName.csproj并纠正follwing设置:

<IISExpressAnonymousAuthentication>disabled</IISExpressAnonymousAuthentication> 
<IISExpressWindowsAuthentication>enabled</IISExpressWindowsAuthentication> 

<UseIIS>True</UseIIS> 
+0

以上回答编辑文件.csproj正在为我工​​作。谢谢@Radim – banny