我需要使用 C# 以编程方式查找用户名。具体来说,我想让系统/网络用户附加到当前进程。我正在编写一个使用 Windows 集成安全性的 Web 应用程序。
minty
问问题
34120 次
3 回答
38
身份的抽象视图通常是IPrincipal
/ IIdentity
:
IPrincipal principal = Thread.CurrentPrincipal;
IIdentity identity = principal == null ? null : principal.Identity;
string name = identity == null ? "" : identity.Name;
这允许相同的代码在许多不同的模型(winform、asp.net、wcf 等)中工作——但它依赖于预先设置的标识(因为它是应用程序定义的)。例如,在 winform 中,您可能会使用当前用户的 windows 身份:
Thread.CurrentPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
但是,主体也可以完全定制 - 它不一定与 Windows 帐户等有关。另一个应用程序可能使用登录屏幕来允许任意用户登录:
string userName = "Fred"; // todo
string[] roles = { "User", "Admin" }; // todo
Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(userName), roles);
于 2008-12-09T05:26:40.903 回答
16
取决于应用程序的上下文。您可以使用 Environment.UserName (console) 或 HttpContext.Current.User.Identity.Name (web)。请注意,使用 Windows 集成身份验证时,您可能需要从用户名中删除域。此外,您可以在代码隐藏中使用页面的 User 属性获取当前用户,而不是从当前 HTTP 上下文中引用它。
于 2008-12-09T00:28:23.360 回答
3
string user = System.Security.Principal.WindowsIdentity.GetCurrent().Name ;
于 2015-02-10T08:24:03.857 回答