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;
}
}
But UserIdentityName returns empty string...
I also have this at my web.config:
<authentication mode="Windows" />
any idea?
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.
For example:
[Authorize]
public ActionResult Index()
{
string user = User.Identity.Name;
...
}
Also make sure that you have enabled Windows Authentication (NTLM) on your web server.
In solution explorer pane select the Web Project and hit F4. (not right click+properties, thats different)
In properties Pane set:
Windows Authentication: Enable
Anonymous Authentication: Disabled
In Web.config: <authentication mode="Windows"></authentication>
To get Username:
HttpContext.Current.User.Identity.Name OR User.Identity.Name
Run your project, Happy Days!
Chaps,
if you are running in IISExpress. Make sure the following setting as below:
In web.config
<authentication mode="Windows"/>
<authorization>
<deny users="?"/>
</authorization>
open the projectName.csproj in notepad and correct the follwing settings:
<IISExpressAnonymousAuthentication>disabled</IISExpressAnonymousAuthentication>
<IISExpressWindowsAuthentication>enabled</IISExpressWindowsAuthentication>
<UseIIS>True</UseIIS>
Try adding:
<authorization>
<deny users="?" />
</authorization>
to deny access to anonymous users.
来源:https://stackoverflow.com/questions/12552950/windows-authentication-in-mvc