我正在尝试获取Thread.CurrentPrincipal.Identity.Name
并且它似乎返回一个空字符串。
我尝试过以管理员身份和其他用户身份运行,但它仍然在执行此操作。如果我转到对象上的Claims
,则发布者为LOCAL AUTHORITY
。这不应该返回我登录的用户吗?
public string GetCurrentUser()
{
var principal = Thread.CurrentPrincipal.Identity.Name;
//Thread.CurrentPrincipal.Identity
return principal;
}
答案 0 :(得分:0)
CurrentPrincipal property uses internal GetThreadPrincipal
method of AppDomain type to build IPrincipal
object by default.
internal IPrincipal GetThreadPrincipal()
{
IPrincipal principal;
if (this._DefaultPrincipal == null)
{
switch (this._PrincipalPolicy)
{
case PrincipalPolicy.UnauthenticatedPrincipal:
principal = (IPrincipal) new GenericPrincipal((IIdentity) new GenericIdentity("", ""), new string[1]
{
""
});
break;
case PrincipalPolicy.NoPrincipal:
principal = (IPrincipal) null;
break;
case PrincipalPolicy.WindowsPrincipal:
principal = (IPrincipal) new WindowsPrincipal(WindowsIdentity.GetCurrent());
break;
default:
principal = (IPrincipal) null;
break;
}
}
else
principal = this._DefaultPrincipal;
return principal;
}
GetThreadPrincipal method uses PrincipalPolicy which is UnauthenticatedPrincipal
by default.
You can change default behavior. For example you can use SetPrincipalPolicy method of AppDomain
with PrincipalPolicy.WindowsPrincipal
to get a Windows user
var appDomain = AppDomain.CurrentDomain;
appDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
var principal = Thread.CurrentPrincipal;
var user = principal.Identity.Name;