【问题标题】:How do you find the users name/Identity in C#如何在 C# 中找到用户名/身份
【发布时间】:2008-12-09 00:23:06
【问题描述】:

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

【问题讨论】:

  • 你的问题太模糊了。您是否正在尝试编写 SQL 查询?使用一些 API?从 Active Directory 获取信息?请准确地说明您要完成的工作。
  • 对不起,我正在编辑更具体的问题。

标签: c# .net windows-authentication identity


【解决方案1】:

身份的抽象视图通常是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);

【讨论】:

  • 一个小补充。在某些情况下,您可能希望为应用程序域的线程设置default principal。可以这样AppDomain.CurrentDomain.SetThreadPrincipal(myPrincipal);
【解决方案2】:

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

【讨论】:

    【解决方案3】:
    string user = System.Security.Principal.WindowsIdentity.GetCurrent().Name ;
    

    【讨论】:

    • 虽然此代码块可能会回答这个问题,但最好能提供一些解释说明为什么这样做。
    猜你喜欢
    • 2011-11-10
    • 2013-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-08
    • 2015-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多