如何在C#中找到用户名/身份

我需要使用C#以编程方式查找用户名。 具体来说,我想让系统/网络用户连接到当前进程。 我正在编写一个使用Windows集成安全性的Web应用程序。

抽象的身份观通常是IPrincipal / IIdentity

 IPrincipal principal = Thread.CurrentPrincipal; IIdentity identity = principal == null ? null : principal.Identity; string name = identity == null ? "" : identity.Name; 

这允许相同的代码在许多不同的模型(winform,asp.net,wcf等)中工作 – 但它依赖于事先设置的身份(因为它是应用程序定义的)。 例如,在winform中,您可以使用当前用户的窗口标识:

 Thread.CurrentPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); 

但是,委托人也可以完全定制 – 它不一定与Windows帐户等有关。另一个应用程序可能使用登录屏幕允许任意用户登录:

 string userName = "Fred"; // todo string[] roles = { "User", "Admin" }; // todo Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(userName), roles); 

取决于应用程序的上下文。 您可以使用Environment.UserName(控制台)或HttpContext.Current.User.Identity.Name(web)。 请注意,使用Windows集成身份validation时,可能需要从用户名中删除域。 此外,您可以使用代码隐藏中的页面的User属性来获取当前用户,而不是从当前HTTP上下文中引用它。

 string user = System.Security.Principal.WindowsIdentity.GetCurrent().Name ;