我需要以编程方式找到用户名称使用C#。具体而言,我想获得附加到当前进程的系统/网络用户。我在写一个使用Windows集成安全性的Web应用程序。
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 that uses windows integrated security.
推荐答案身份的抽象看法往往是的IPrincipal / 的IIdentity :
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;这允许同一code在许多不同的模式(的winform,asp,WCF等)的工作 - 但它依赖于身份被预先设置(因为它是应用程序定义)。例如,在一个WinForm你可能会使用当前用户的Windows身份:
This allows the same code to work in many different models (winform, asp, 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());
不过,校长也可以完全定制 - 它并不一定涉及到Windows帐户等。另一个应用程序可能会使用一个登录界面,允许任意用户登录:
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);更多推荐
你如何找到在C#中的用户名/身份
发布评论