You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C# MVC中获取不带域名的Windows当前登录用户全名

获取Windows登录用户的全名(不带域名)

我来帮你搞定这个问题!你当前用代码拿到的是带域名的身份标识(比如APAC\san123),要获取用户的全名(也就是AD中配置的显示名称),可以分两步实现:

第一步:提取不带域名的用户名

不管你用哪条语句获取到带域名的用户名,都可以通过Split方法拆分出纯用户名:

// 以HttpContext的用户身份为例
string fullIdentity = System.Web.HttpContext.Current.User.Identity.Name;
// 按反斜杠拆分,取第二部分就是纯用户名
string userName = fullIdentity.Split('\\')[1];

如果担心拆分异常(比如没有域名的特殊情况),可以加个简单判断:

string[] identityParts = fullIdentity.Split('\\');
string userName = identityParts.Length == 2 ? identityParts[1] : fullIdentity;

第二步:通过AD查询用户全名

要获取用户的全名,需要查询Active Directory(AD),这里有两种常用方法:

方法1:使用AccountManagement(推荐,封装更友好)

这个命名空间是AD操作的上层封装,用起来简洁省心:

  1. 先在项目中添加引用:System.DirectoryServices.AccountManagement
  2. 编写查询代码:
using System.DirectoryServices.AccountManagement;

public string GetUserFullName()
{
    string fullIdentity = System.Web.HttpContext.Current.User.Identity.Name;
    string[] identityParts = fullIdentity.Split('\\');
    if (identityParts.Length != 2)
        return fullIdentity;

    string domain = identityParts[0];
    string userName = identityParts[1];

    try
    {
        // 连接到目标域
        using (PrincipalContext context = new PrincipalContext(ContextType.Domain, domain))
        {
            // 根据用户名查找用户
            UserPrincipal user = UserPrincipal.FindByIdentity(context, userName);
            if (user != null)
            {
                // 返回显示名称,如果为空则返回用户名作为备选
                return user.DisplayName ?? userName;
            }
        }
    }
    catch (Exception ex)
    {
        // 这里可以加日志记录异常(比如无法连接AD)
        // 异常情况下返回用户名兜底
        return userName;
    }

    return userName;
}

方法2:使用DirectoryServices(底层更灵活)

如果你需要更底层的AD操作控制,可以用这个方法:

  1. 添加引用:System.DirectoryServices
  2. 代码示例:
using System.DirectoryServices;

public string GetUserFullName()
{
    string fullIdentity = System.Web.HttpContext.Current.User.Identity.Name;
    string[] identityParts = fullIdentity.Split('\\');
    if (identityParts.Length != 2)
        return fullIdentity;

    string domain = identityParts[0];
    string userName = identityParts[1];

    try
    {
        // 连接到域
        DirectoryEntry domainEntry = new DirectoryEntry($"LDAP://{domain}");
        // 创建搜索器,过滤条件为用户对象且用户名匹配
        DirectorySearcher searcher = new DirectorySearcher(domainEntry);
        searcher.Filter = $"(&(objectClass=user)(sAMAccountName={userName}))";
        // 指定要加载的属性(显示名称)
        searcher.PropertiesToLoad.Add("displayName");
        
        SearchResult result = searcher.FindOne();
        if (result != null && result.Properties["displayName"].Count > 0)
        {
            return result.Properties["displayName"][0].ToString();
        }
    }
    catch (Exception ex)
    {
        // 异常处理逻辑
        return userName;
    }

    return userName;
}

注意事项

  • 确保你的MVC项目已经启用Windows身份验证,在web.config中配置:
<system.web>
  <authentication mode="Windows" />
  <authorization>
    <deny users="?" /> <!-- 拒绝匿名访问 -->
  </authorization>
</system.web>
  • 应用池的运行身份需要有访问AD的权限,否则会出现查询失败的情况。

内容的提问来源于stack exchange,提问作者sandeep

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 16:02:50