How do I get the currently loggedin Windows account from an ASP.NET page?

前端 未结 8 1014
余生分开走
余生分开走 2020-12-01 12:25

I have an ASP.NET 3.5 application that uses ASP.NET forms authentication. I want to be able to get the Windows user name currently logged into the computer (NOT logged into

8条回答
  •  囚心锁ツ
    2020-12-01 12:49

    Try with the below line of code:

    string loggedOnUser = string.Empty;
     loggedOnUser = Request.ServerVariables.Get("AUTH_USER");
    

    You may not be getting the values when you run the application from Visual Studio... Check it after deployed in IIS.

    For getting the User name, use:

    string userName = string.Empty;
    using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "Your Domain Name"))
    {
        UserPrincipal user = new UserPrincipal(pc);
        user = UserPrincipal.FindByIdentity(pc, "User ID Will Come here");
        if (user != null)
        {
            userName = user.GivenName + " " + user.Surname;
    
        }
        else
        {
            //return string.Empty;
            userName = "User Not Found";
        }
    }
    

提交回复
热议问题