目标
我有一个使用 Windows 身份验证的 WCF 服务。我想确定连接的用户的全名。用户可以是域用户或本地用户。对于本地用户,可以在[计算机管理(本地)>本地用户和组>用户>[用户]>全名]中查看全名。
FindByIdentity 几乎成功
我可以使用 UserPrincipal.FindByIdentity() 来检索 UserPrincipal 对象,然后从 UserPrincipal.DisplayName 中获取它。 FindByIdentity 的第一个参数需要指定 ContextType,例如 Domain 或 Machine。
所以我想避免猜测。
问题
目前的代码
string GetFullName()
{
using (var ctx = new PrincipalContext(ContextType.Domain))
{
string userName = OperationContext.Current.ServiceSecurityContext.WindowsIdentity.Name;
UserPrincipal u = UserPrincipal.FindByIdentity(ctx, userName);
return u.DisplayName;
}
}
答案 0 :(得分:0)
您可以使用 Environment.UserDomainName 属性获取当前用户的域名。如果未加入域,则返回当前用户的主机名。
答案 1 :(得分:0)
我现在正在使用以下内容。如果有人有更好的想法,请发表您的答案
bool LocalUserConnected()
{
string userName = OperationContext.Current.ServiceSecurityContext.WindowsIdentity.Name;
return userName.StartsWith(Environment.MachineName + @"\");
}