MVC中的Windows身份验证

问题描述:

我要检查使用Windows身份验证的用户的登录名。
我有这个作为我的控制器的构造方法:

I want to check the login name of a user using windows authentication. I have this as a constructor of my controller:

public class HomeController : BaseController
{
    public string UserIdentityName;

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

但UserIdentityName返回空字符串...

But UserIdentityName returns empty string...

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

I also have this at my web.config:

<authentication mode="Windows" />   

任何想法?

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

Don't try to access any HttpContext related stuff in your controller's constructor. The earliest stage where you should be accessing it is Initialize method or inside the controller actions.

例如:

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

另外,还要确保您已启用Windows身份验证在Web服务器上(NTLM)。

Also make sure that you have enabled Windows Authentication (NTLM) on your web server.