Getting Current User in .NET Core Console
System.Security.Principal.Windows
is not available unless you import the DLL manually. The following worked for me:
Environment.UserName;
According to the .NET Core System.Environment Source Code, this solution "should suffice in 99% of cases."
Note: Be sure you are targeting DotNetCore 2.0
or later as 1.0
and 1.1
do not have this definition.
Edit Jan 22 2019: The link to the old source of the method has gone stale. PR 34654 moved System.Environment
to live in CoreLib
. For those curious to read the source code, you may still do so, though the comment suggesting it "should suffice in 99% of cases" has been removed.
Got it. A possible option is to use WindowsIdentity:
WindowsIdentity.GetCurrent().Name
It is necessary to add the System.Security.Principal.Windows package. Of course, this is for Windows only.
Another option is to use Claims:
ClaimsPrincipal.Current
For that, the package to add is System.Security.Claims. In Windows, by default, the identity will be empty.
If you want to reuse IIdentity
abstraction to pass through your middle layer do this:
var identity = new GenericIdentity(Environment.UserDomainName + "\\" + Environment.UserName, "Anonymous");
P.S. in core 2 console app:
ClaimsPrincipal.Current
and Thread.CurrentPrincipal
are always null (unless you have setup them) and this code will not work either:
IPrincipal principal = new GenericPrincipal(identity, null);
AppDomain.CurrentDomain.SetThreadPrincipal(principal);
after this ClaimsPrincipal.Current
and Thread.CurrentPrincipal
are still null.
WindowsIdentity.GetCurrent()
works, but there should be more strong reasons to reference System.Security.Principal.Window
then get the "user name".