How do you find the users name/Identity in C#

后端 未结 3 1949
名媛妹妹
名媛妹妹 2020-12-18 19:44

I need to programatically find the users name using C#. Specifically, I want to get the system/network user attached to the current process. I\'m writing a web application t

3条回答
  •  一整个雨季
    2020-12-18 20:44

    The abstracted view of identity is often the IPrincipal/IIdentity:

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

    This allows the same code to work in many different models (winform, asp.net, wcf, etc) - but it relies on the identity being set in advance (since it is application-defined). For example, in a winform you might use the current user's windows identity:

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

    However, the principal can also be completely bespoke - it doesn't necessarily relate to windows accounts etc. Another app might use a login screen to allow arbitrary users to log on:

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

提交回复
热议问题