你如何在 C# 中找到用户名/身份

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/351415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 00:10:35  来源:igfitidea点击:

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

c#.netwindows-authenticationidentity

提问by minty

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.

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

回答by tvanfosson

Depends on the context of the application. You can use Environment.UserName (console) or HttpContext.Current.User.Identity.Name (web). Note that when using Windows integrated authentication, you may need to remove the domain from the user name. Also, you can get the current user using the User property of the page in codebehind, rather than referencing it from the current HTTP context.

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

回答by Marc Gravell

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

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

这允许相同的代码在许多不同的模型(winform、asp.net、wcf 等)中工作 - 但它依赖于预先设置的身份(因为它是应用程序定义的)。例如,在 winform 中,您可以使用当前用户的 Windows 身份:

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:

但是,主体也可以完全定制 - 它不一定与 Windows 帐户等相关。另一个应用程序可能使用登录屏幕来允许任意用户登录:

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

回答by Mehdi Bugnard

string user = System.Security.Principal.WindowsIdentity.GetCurrent().Name ;