MVC中的Windows身份验证

Guy*_*y Z 4 authentication asp.net-mvc windows-authentication asp.net-mvc-4

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

public class HomeController : BaseController
{
    public string UserIdentityName;

    public HomeController()
    {
        UserIdentityName = System.Web.HttpContext.Current.User.Identity.Name;// HttpContext.Current.User.Identity.Name;
    }
}
Run Code Online (Sandbox Code Playgroud)

但UserIdentityName返回空字符串...

我在web.config上也有这个:

<authentication mode="Windows" />   
Run Code Online (Sandbox Code Playgroud)

任何的想法?

Moj*_*oji 12

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

在属性窗格中设置:
Windows身份验证:启用
匿名身份验证:已禁用

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

获取用户名:

HttpContext.Current.User.Identity.Name OR User.Identity.Name
Run Code Online (Sandbox Code Playgroud)

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


Dar*_*rov 5

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

例如:

[Authorize]
public ActionResult Index()
{
    string user = User.Identity.Name;
    ...
}
Run Code Online (Sandbox Code Playgroud)

还要确保已在Web服务器上启用Windows身份验证(NTLM).