如何使用不同的方法获取Windows用户名?
在.NET 中,似乎有多种方法可以获取当前的Windows 用户名。其中三个是:
string name = WindowsIdentity.GetCurrent().Name;
或
string name = Thread.CurrentPrincipal.Identity.Name;
或
string name = Environment.UserName;
有什么区别,为什么选择一种方法而不是另一种?还有其他方法吗?
In .NET, there appears to be several ways to get the current Windows user name. Three of which are:
string name = WindowsIdentity.GetCurrent().Name;
or
string name = Thread.CurrentPrincipal.Identity.Name;
or
string name = Environment.UserName;
What's the difference, and why choose one method over the other? Are there any other ways?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Environment.UserName 在 advapi32.dll 中调用 GetUserName。这意味着如果您冒充另一个用户,此属性将反映这一点。
Thread.CurrentPrincipal 有一个 setter,可以通过编程方式进行更改。 (顺便说一句,这不是模拟。)
WindowsIdentity 是您当前的 Windows 身份(如果有)。它不一定反映用户,想想带有 FormsAuthentication 的 ASP.NET。那么 WindowsIdentity 将是 NT 服务,但 FormsIdentity 将是登录用户。还有一个 PassportIdentity,您可以构建自己的东西以使事情进一步复杂化。
Environment.UserName calls GetUserName within advapi32.dll. This means that if you're impersonating another user, this property will reflect that.
Thread.CurrentPrincipal has a setter and can be changed programmatically. (This is not impersonation btw.)
WindowsIdentity is your current windows identity, if any. It will not necessarily reflect the user, think ASP.NET with FormsAuthentication. Then the WindowsIdentity will be the NT-service, but the FormsIdentity will be the logged in user. There's also a PassportIdentity, and you can build your own stuff to complicate things further.
您要求替代方法。
当然,您始终可以使用本机 Windows API: GetUserName 。
You asked for alternative ways.
Of course, you can always use the native Windows API: GetUserName.
我相信该属性被放置在几个地方,以便程序员更容易找到。只有一名登录用户,并且只有一个相应的名称。
I believe the property was put in several places so that it would be easier for the programmer to find. There's only one logged in user, and only one respective name.
这三个方法的描述如下:
HttpContext = HttpContext.Current.User,返回一个 IPrincipal 对象,其中包含当前 Web 请求的安全信息。这是经过身份验证的 Web 客户端。
WindowsIdentity = WindowsIdentity.GetCurrent(),返回当前执行的 Win32 线程的安全上下文的标识。
Thread = Thread.CurrentPrincipal 返回当前执行的 .NET 线程的主体,该线程位于 Win32 线程之上。
它们的结果会根据您的 IIS 配置而变化,如本文所述:
http://msdn.microsoft.com/en-us/library/aa302377.aspx
The three methods are described as follow:
HttpContext = HttpContext.Current.User, which returns an IPrincipal object that contains security information for the current Web request. This is the authenticated Web client.
WindowsIdentity = WindowsIdentity.GetCurrent(), which returns the identity of the security context of the currently executing Win32 thread.
Thread = Thread.CurrentPrincipal which returns the principal of the currently executing .NET thread which rides on top of the Win32 thread.
And they change in result depending on your IIS configuration as explained in this article:
http://msdn.microsoft.com/en-us/library/aa302377.aspx