代码之家  ›  专栏  ›  技术社区  ›  minty

如何在C中找到用户名/标识#

  •  16
  • minty  · 技术社区  · 17 年前

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

    3 回复  |  直到 11 年前
        1
  •  37
  •   Chris Schiffhauer aleha_84    12 年前

    抽象的身份观通常是 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);
    
        2
  •  16
  •   tvanfosson    17 年前

    取决于应用程序的上下文。您可以使用environment.user name(console)或httpcontext.current.user.identity.name(web)。请注意,使用Windows集成身份验证时,可能需要从用户名中删除该域。另外,您可以在codeboond中使用页面的user属性来获取当前用户,而不是从当前http上下文中引用它。

        3
  •  3
  •   Mehdi Bugnard    11 年前
    string user = System.Security.Principal.WindowsIdentity.GetCurrent().Name ;