在 .NET Core 控制台中获取当前用户

Getting Current User in .NET Core Console

在 .NET Core 控制台应用程序中(注意:不是 ASP.NET Core!),如何获取当前用户?需要明确的是,我正在寻找以前可用的 Thread.CurrentPrincipal,但现在已不存在。 PlatformServices 不包含此信息,Environment 也不包含。

知道了。一个可能的选择是使用 WindowsIdentity:

WindowsIdentity.GetCurrent().Name

需要添加System.Security.Principal.Windows包。 当然,这仅适用于 Windows。

另一种选择是使用声明:

ClaimsPrincipal.Current

为此,要添加的包是 System.Security.Claims。在Windows中,默认情况下,标识将为空。

除非您手动导入 DLL,否则

System.Security.Principal.Windows 不可用。以下对我有用:

Environment.UserName;

根据.NET Core System.Environment Source Code,这个解决方案"should suffice in 99% of cases."

注意:确保您的目标是 DotNetCore 2.0 或更高版本,因为 1.01.1 没有此定义。

2019 年 1 月 22 日编辑:link 该方法的旧来源已经过时。 PR 34654 moved System.Environment to live in CoreLib. For those curious to read the source code,您仍然可以这样做,尽管建议 "should suffice in 99% of cases" 的评论已被删除。

如果您想重用 IIdentity 抽象来通过中间层,请执行以下操作:

var identity = new GenericIdentity(Environment.UserDomainName + "\" + Environment.UserName, "Anonymous");

P.S。在核心 2 控制台应用程序中: ClaimsPrincipal.CurrentThread.CurrentPrincipal 始终为空(除非您已设置它们)并且此代码也不起作用:

IPrincipal principal = new GenericPrincipal(identity, null);
AppDomain.CurrentDomain.SetThreadPrincipal(principal);

此后 ClaimsPrincipal.CurrentThread.CurrentPrincipal 仍然为空。

WindowsIdentity.GetCurrent() 有效,但应该有更充分的理由引用 System.Security.Principal.Window 然后得到 "user name".